summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rwxr-xr-xsrc/conf_mode/firewall.py11
-rwxr-xr-xsrc/conf_mode/interfaces_bridge.py3
-rwxr-xr-xsrc/conf_mode/interfaces_ethernet.py34
-rwxr-xr-xsrc/conf_mode/interfaces_wireguard.py28
-rwxr-xr-xsrc/conf_mode/nat.py13
-rwxr-xr-xsrc/conf_mode/pki.py7
-rwxr-xr-xsrc/conf_mode/policy.py16
-rwxr-xr-xsrc/conf_mode/qos.py8
-rwxr-xr-xsrc/conf_mode/service_ipoe-server.py6
-rwxr-xr-xsrc/conf_mode/service_monitoring_prometheus.py18
-rwxr-xr-xsrc/conf_mode/service_pppoe-server.py4
-rwxr-xr-xsrc/conf_mode/service_ssh.py76
-rwxr-xr-xsrc/conf_mode/system_ip.py5
-rwxr-xr-xsrc/conf_mode/system_login.py40
-rwxr-xr-xsrc/conf_mode/vpn_ipsec.py2
-rwxr-xr-xsrc/conf_mode/vpn_openconnect.py2
-rwxr-xr-xsrc/etc/opennhrp/opennhrp-script.py371
-rwxr-xr-xsrc/helpers/run-config-migration.py7
-rwxr-xr-xsrc/helpers/set_vyconf_backend.py39
-rwxr-xr-xsrc/helpers/teardown-config-session.py30
-rwxr-xr-xsrc/init/vyos-router112
-rwxr-xr-xsrc/op_mode/image_info.py8
-rwxr-xr-xsrc/op_mode/image_installer.py8
-rw-r--r--src/services/api/rest/models.py18
-rw-r--r--src/services/api/rest/routers.py35
-rw-r--r--src/systemd/opennhrp.service13
-rw-r--r--src/systemd/vyconfd.service2
-rw-r--r--src/tests/test_template.py5
-rwxr-xr-xsrc/validators/bgp-large-community-list21
29 files changed, 441 insertions, 501 deletions
diff --git a/src/conf_mode/firewall.py b/src/conf_mode/firewall.py
index 274ca2ce6..348eaeba3 100755
--- a/src/conf_mode/firewall.py
+++ b/src/conf_mode/firewall.py
@@ -17,6 +17,8 @@
import os
import re
+from glob import glob
+
from sys import exit
from vyos.base import Warning
from vyos.config import Config
@@ -30,6 +32,7 @@ from vyos.firewall import geoip_update
from vyos.template import render
from vyos.utils.dict import dict_search_args
from vyos.utils.dict import dict_search_recursive
+from vyos.utils.file import write_file
from vyos.utils.process import call
from vyos.utils.process import cmd
from vyos.utils.process import rc_cmd
@@ -37,7 +40,6 @@ from vyos.utils.network import get_vrf_members
from vyos.utils.network import get_interface_vrf
from vyos import ConfigError
from vyos import airbag
-from pathlib import Path
from subprocess import run as subp_run
airbag.enable()
@@ -626,10 +628,11 @@ def apply(firewall):
domain_action = 'restart'
if dict_search_args(firewall, 'group', 'remote_group') or dict_search_args(firewall, 'group', 'domain_group') or firewall['ip_fqdn'].items() or firewall['ip6_fqdn'].items():
text = f'# Automatically generated by firewall.py\nThis file indicates that vyos-domain-resolver service is used by the firewall.\n'
- Path(domain_resolver_usage).write_text(text)
+ write_file(domain_resolver_usage, text)
else:
- Path(domain_resolver_usage).unlink(missing_ok=True)
- if not Path('/run').glob('use-vyos-domain-resolver*'):
+ if os.path.exists(domain_resolver_usage):
+ os.unlink(domain_resolver_usage)
+ if not glob('/run/use-vyos-domain-resolver*'):
domain_action = 'stop'
call(f'systemctl {domain_action} vyos-domain-resolver.service')
diff --git a/src/conf_mode/interfaces_bridge.py b/src/conf_mode/interfaces_bridge.py
index 95dcc543e..c14e6a599 100755
--- a/src/conf_mode/interfaces_bridge.py
+++ b/src/conf_mode/interfaces_bridge.py
@@ -167,6 +167,9 @@ def verify(bridge):
if 'has_vrf' in interface_config:
raise ConfigError(error_msg + 'it has a VRF assigned!')
+ if 'bpdu_guard' in interface_config and 'root_guard' in interface_config:
+ raise ConfigError(error_msg + 'bpdu-guard and root-guard cannot be configured at the same time!')
+
if 'enable_vlan' in bridge:
if 'has_vlan' in interface_config:
raise ConfigError(error_msg + 'it has VLAN subinterface(s) assigned!')
diff --git a/src/conf_mode/interfaces_ethernet.py b/src/conf_mode/interfaces_ethernet.py
index 41c89fdf8..13d3e82e9 100755
--- a/src/conf_mode/interfaces_ethernet.py
+++ b/src/conf_mode/interfaces_ethernet.py
@@ -22,6 +22,7 @@ from vyos.base import Warning
from vyos.config import Config
from vyos.configdict import get_interface_dict
from vyos.configdict import is_node_changed
+from vyos.configdict import get_flowtable_interfaces
from vyos.configverify import verify_address
from vyos.configverify import verify_dhcpv6
from vyos.configverify import verify_interface_exists
@@ -168,6 +169,8 @@ def get_config(config=None):
tmp = is_node_changed(conf, base + [ifname, 'evpn'])
if tmp: ethernet.update({'frr_dict' : get_frrender_dict(conf)})
+ ethernet['flowtable_interfaces'] = get_flowtable_interfaces(conf)
+
return ethernet
def verify_speed_duplex(ethernet: dict, ethtool: Ethtool):
@@ -269,7 +272,38 @@ def verify_allowedbond_changes(ethernet: dict):
f' on interface "{ethernet["ifname"]}".' \
f' Interface is a bond member')
+def verify_flowtable(ethernet: dict):
+ ifname = ethernet['ifname']
+
+ if 'deleted' in ethernet and ifname in ethernet['flowtable_interfaces']:
+ raise ConfigError(f'Cannot delete interface "{ifname}", still referenced on a flowtable')
+
+ if 'vif_remove' in ethernet:
+ for vif in ethernet['vif_remove']:
+ vifname = f'{ifname}.{vif}'
+
+ if vifname in ethernet['flowtable_interfaces']:
+ raise ConfigError(f'Cannot delete interface "{vifname}", still referenced on a flowtable')
+
+ if 'vif_s_remove' in ethernet:
+ for vifs in ethernet['vif_s_remove']:
+ vifsname = f'{ifname}.{vifs}'
+
+ if vifsname in ethernet['flowtable_interfaces']:
+ raise ConfigError(f'Cannot delete interface "{vifsname}", still referenced on a flowtable')
+
+ if 'vif_s' in ethernet:
+ for vifs, vifs_conf in ethernet['vif_s'].items():
+ if 'vif_c_delete' in vifs_conf:
+ for vifc in vifs_conf['vif_c_delete']:
+ vifcname = f'{ifname}.{vifs}.{vifc}'
+
+ if vifcname in ethernet['flowtable_interfaces']:
+ raise ConfigError(f'Cannot delete interface "{vifcname}", still referenced on a flowtable')
+
def verify(ethernet):
+ verify_flowtable(ethernet)
+
if 'deleted' in ethernet:
return None
if 'is_bond_member' in ethernet:
diff --git a/src/conf_mode/interfaces_wireguard.py b/src/conf_mode/interfaces_wireguard.py
index 3ca6ecdca..770667df1 100755
--- a/src/conf_mode/interfaces_wireguard.py
+++ b/src/conf_mode/interfaces_wireguard.py
@@ -14,6 +14,9 @@
# 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
@@ -35,7 +38,6 @@ from vyos.utils.network import is_wireguard_key_pair
from vyos.utils.process import call
from vyos import ConfigError
from vyos import airbag
-from pathlib import Path
airbag.enable()
@@ -145,19 +147,11 @@ def generate(wireguard):
def apply(wireguard):
check_kmod('wireguard')
- if 'rebuild_required' in wireguard or 'deleted' in wireguard:
- wg = WireGuardIf(**wireguard)
- # WireGuard only supports peer removal based on the configured public-key,
- # by deleting the entire interface this is the shortcut instead of parsing
- # out all peers and removing them one by one.
- #
- # Peer reconfiguration will always come with a short downtime while the
- # WireGuard interface is recreated (see below)
- wg.remove()
+ wg = WireGuardIf(**wireguard)
- # Create the new interface if required
- if 'deleted' not in wireguard:
- wg = WireGuardIf(**wireguard)
+ if 'deleted' in wireguard:
+ wg.remove()
+ else:
wg.update(wireguard)
domain_resolver_usage = '/run/use-vyos-domain-resolver-interfaces-wireguard-' + wireguard['ifname']
@@ -168,12 +162,12 @@ def apply(wireguard):
from vyos.utils.file import write_file
text = f'# Automatically generated by interfaces_wireguard.py\nThis file indicates that vyos-domain-resolver service is used by the interfaces_wireguard.\n'
- text += "intefaces:\n" + "".join([f" - {peer}\n" for peer in wireguard['peers_need_resolve']])
- Path(domain_resolver_usage).write_text(text)
+ text += "interfaces:\n" + "".join([f" - {peer}\n" for peer in wireguard['peers_need_resolve']])
write_file(domain_resolver_usage, text)
else:
- Path(domain_resolver_usage).unlink(missing_ok=True)
- if not Path('/run').glob('use-vyos-domain-resolver*'):
+ if os.path.exists(domain_resolver_usage):
+ os.unlink(domain_resolver_usage)
+ if not glob('/run/use-vyos-domain-resolver*'):
domain_action = 'stop'
call(f'systemctl {domain_action} vyos-domain-resolver.service')
diff --git a/src/conf_mode/nat.py b/src/conf_mode/nat.py
index 504b3e82a..a938021ba 100755
--- a/src/conf_mode/nat.py
+++ b/src/conf_mode/nat.py
@@ -16,8 +16,8 @@
import os
+from glob import glob
from sys import exit
-from pathlib import Path
from vyos.base import Warning
from vyos.config import Config
@@ -31,7 +31,6 @@ from vyos.utils.file import write_file
from vyos.utils.process import cmd
from vyos.utils.process import run
from vyos.utils.process import call
-from vyos.utils.network import is_addr_assigned
from vyos.utils.network import interface_exists
from vyos.firewall import fqdn_config_parse
from vyos import ConfigError
@@ -176,12 +175,6 @@ def verify(nat):
if 'exclude' not in config and 'backend' not in config['load_balance']:
raise ConfigError(f'{err_msg} translation requires address and/or port')
- addr = dict_search('translation.address', config)
- if addr != None and addr != 'masquerade' and not is_ip_network(addr):
- for ip in addr.split('-'):
- if not is_addr_assigned(ip):
- Warning(f'IP address {ip} does not exist on the system!')
-
# common rule verification
verify_rule(config, err_msg, nat['firewall_group'])
@@ -265,9 +258,9 @@ def apply(nat):
text = f'# Automatically generated by nat.py\nThis file indicates that vyos-domain-resolver service is used by nat.\n'
write_file(domain_resolver_usage, text)
elif os.path.exists(domain_resolver_usage):
- Path(domain_resolver_usage).unlink(missing_ok=True)
+ os.unlink(domain_resolver_usage)
- if not Path('/run').glob('use-vyos-domain-resolver*'):
+ if not glob('/run/use-vyos-domain-resolver*'):
domain_action = 'stop'
call(f'systemctl {domain_action} vyos-domain-resolver.service')
diff --git a/src/conf_mode/pki.py b/src/conf_mode/pki.py
index 869518dd9..7d01b6642 100755
--- a/src/conf_mode/pki.py
+++ b/src/conf_mode/pki.py
@@ -64,6 +64,10 @@ sync_search = [
'path': ['service', 'https'],
},
{
+ 'keys': ['key'],
+ 'path': ['service', 'ssh'],
+ },
+ {
'keys': ['certificate', 'ca_certificate'],
'path': ['interfaces', 'ethernet'],
},
@@ -414,7 +418,8 @@ def verify(pki):
if 'country' in default_values:
country = default_values['country']
if len(country) != 2 or not country.isalpha():
- raise ConfigError(f'Invalid default country value. Value must be 2 alpha characters.')
+ raise ConfigError('Invalid default country value. '\
+ 'Value must be 2 alpha characters.')
if 'changed' in pki:
# if the list is getting longer, we can move to a dict() and also embed the
diff --git a/src/conf_mode/policy.py b/src/conf_mode/policy.py
index a90e33e81..ec9005890 100755
--- a/src/conf_mode/policy.py
+++ b/src/conf_mode/policy.py
@@ -14,6 +14,7 @@
# 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 re
from sys import exit
from vyos.config import Config
@@ -24,9 +25,20 @@ from vyos.frrender import get_frrender_dict
from vyos.utils.dict import dict_search
from vyos.utils.process import is_systemd_service_running
from vyos import ConfigError
+from vyos.base import Warning
from vyos import airbag
airbag.enable()
+# Sanity checks for large-community-list regex:
+# * Require complete 3-tuples, no blank members. Catch missed & doubled colons.
+# * Permit appropriate community separators (whitespace, underscore)
+# * Permit common regex between tuples while requiring at least one separator
+# (eg, "1:1:1_.*_4:4:4", matching "1:1:1 4:4:4" and "1:1:1 2:2:2 4:4:4",
+# but not "1:1:13 24:4:4")
+# Best practice: stick with basic patterns, mind your wildcards and whitespace.
+# Regex that doesn't match this pattern will be allowed with a warning.
+large_community_regex_pattern = r'([^: _]+):([^: _]+):([^: _]+)([ _]([^:]+):([^: _]+):([^: _]+))*'
+
def community_action_compatibility(actions: dict) -> bool:
"""
Check compatibility of values in community and large community sections
@@ -147,6 +159,10 @@ def verify(config_dict):
if 'regex' not in rule_config:
raise ConfigError(f'A regex {mandatory_error}')
+ if policy_type == 'large_community_list':
+ if not re.fullmatch(large_community_regex_pattern, rule_config['regex']):
+ Warning(f'"policy large-community-list {instance} rule {rule} regex" does not follow expected form and may not match as expected.')
+
if policy_type in ['prefix_list', 'prefix_list6']:
if 'prefix' not in rule_config:
raise ConfigError(f'A prefix {mandatory_error}')
diff --git a/src/conf_mode/qos.py b/src/conf_mode/qos.py
index 59e307a39..aed9407de 100755
--- a/src/conf_mode/qos.py
+++ b/src/conf_mode/qos.py
@@ -85,7 +85,13 @@ def _clean_conf_dict(conf):
}
"""
if isinstance(conf, dict):
- return {node: _clean_conf_dict(val) for node, val in conf.items() if val != {} and _clean_conf_dict(val) != {}}
+ preserve_empty_nodes = {'syn', 'ack'}
+
+ return {
+ node: _clean_conf_dict(val)
+ for node, val in conf.items()
+ if (val != {} and _clean_conf_dict(val) != {}) or node in preserve_empty_nodes
+ }
else:
return conf
diff --git a/src/conf_mode/service_ipoe-server.py b/src/conf_mode/service_ipoe-server.py
index a14d4b5b6..083c27523 100755
--- a/src/conf_mode/service_ipoe-server.py
+++ b/src/conf_mode/service_ipoe-server.py
@@ -88,6 +88,12 @@ def verify(ipoe):
'Can configure username with Lua script only for RADIUS authentication'
)
+ if dict_search('external_dhcp.dhcp_relay', iface_config):
+ if not dict_search('external_dhcp.giaddr', iface_config):
+ raise ConfigError(
+ f'"external-dhcp dhcp-relay" requires "giaddr" to be set for interface {interface}'
+ )
+
verify_accel_ppp_authentication(ipoe, local_users=False)
verify_accel_ppp_ip_pool(ipoe)
verify_accel_ppp_name_servers(ipoe)
diff --git a/src/conf_mode/service_monitoring_prometheus.py b/src/conf_mode/service_monitoring_prometheus.py
index 9a07d8593..f55b09f6c 100755
--- a/src/conf_mode/service_monitoring_prometheus.py
+++ b/src/conf_mode/service_monitoring_prometheus.py
@@ -48,9 +48,21 @@ def get_config(config=None):
if not conf.exists(base):
return None
- monitoring = conf.get_config_dict(
- base, key_mangling=('-', '_'), get_first_key=True, with_recursive_defaults=True
- )
+ monitoring = {}
+ exporters = {
+ 'node_exporter': base + ['node-exporter'],
+ 'frr_exporter': base + ['frr-exporter'],
+ 'blackbox_exporter': base + ['blackbox-exporter'],
+ }
+
+ for exporter_name, exporter_base in exporters.items():
+ if conf.exists(exporter_base):
+ monitoring[exporter_name] = conf.get_config_dict(
+ exporter_base,
+ key_mangling=('-', '_'),
+ get_first_key=True,
+ with_recursive_defaults=True,
+ )
tmp = is_node_changed(conf, base + ['node-exporter', 'vrf'])
if tmp:
diff --git a/src/conf_mode/service_pppoe-server.py b/src/conf_mode/service_pppoe-server.py
index ac697c509..f7cb3dcba 100755
--- a/src/conf_mode/service_pppoe-server.py
+++ b/src/conf_mode/service_pppoe-server.py
@@ -73,7 +73,9 @@ def get_config(config=None):
# https://phabricator.accel-ppp.org/T3
conditions = [is_node_changed(conf, base + ['client-ip-pool']),
is_node_changed(conf, base + ['client-ipv6-pool']),
- is_node_changed(conf, base + ['interface'])]
+ is_node_changed(conf, base + ['interface']),
+ is_node_changed(conf, base + ['authentication','radius','dynamic-author']),
+ is_node_changed(conf, base + ['authentication','mode'])]
if any(conditions):
pppoe.update({'restart_required': {}})
pppoe['server_type'] = 'pppoe'
diff --git a/src/conf_mode/service_ssh.py b/src/conf_mode/service_ssh.py
index 759f87bb2..3d38d940a 100755
--- a/src/conf_mode/service_ssh.py
+++ b/src/conf_mode/service_ssh.py
@@ -23,14 +23,15 @@ from syslog import LOG_INFO
from vyos.config import Config
from vyos.configdict import is_node_changed
from vyos.configverify import verify_vrf
-from vyos.configverify import verify_pki_ca_certificate
+from vyos.configverify import verify_pki_openssh_key
+from vyos.defaults import config_files
from vyos.utils.process import call
from vyos.template import render
from vyos import ConfigError
from vyos import airbag
-from vyos.pki import find_chain
-from vyos.pki import encode_certificate
-from vyos.pki import load_certificate
+from vyos.pki import encode_public_key
+from vyos.pki import load_openssh_public_key
+from vyos.utils.dict import dict_search_recursive
from vyos.utils.file import write_file
airbag.enable()
@@ -44,8 +45,7 @@ key_rsa = '/etc/ssh/ssh_host_rsa_key'
key_dsa = '/etc/ssh/ssh_host_dsa_key'
key_ed25519 = '/etc/ssh/ssh_host_ed25519_key'
-trusted_user_ca_key = '/etc/ssh/trusted_user_ca_key'
-
+trusted_user_ca = config_files['sshd_user_ca']
def get_config(config=None):
if config:
@@ -55,10 +55,8 @@ def get_config(config=None):
base = ['service', 'ssh']
if not conf.exists(base):
return None
-
- ssh = conf.get_config_dict(
- base, key_mangling=('-', '_'), get_first_key=True, with_pki=True
- )
+ ssh = conf.get_config_dict(base, key_mangling=('-', '_'),
+ get_first_key=True, with_pki=True)
tmp = is_node_changed(conf, base + ['vrf'])
if tmp:
@@ -68,14 +66,27 @@ def get_config(config=None):
# options which we need to update into the dictionary retrived.
ssh = conf.merge_defaults(ssh, recursive=True)
- # pass config file path - used in override template
- ssh['config_file'] = config_file
-
# Ignore default XML values if config doesn't exists
# Delete key from dict
if not conf.exists(base + ['dynamic-protection']):
del ssh['dynamic_protection']
+ # See if any user has specified a list of principal names that are accepted
+ # for certificate authentication.
+ tmp = conf.get_config_dict(['system', 'login', 'user'],
+ key_mangling=('-', '_'),
+ no_tag_node_value_mangle=True,
+ get_first_key=True)
+
+ for value, _ in dict_search_recursive(tmp, 'principal'):
+ # Only enable principal handling if SSH trusted-user-ca is set
+ if 'trusted_user_ca' in ssh:
+ ssh['has_principals'] = {}
+ # We do only need to execute this code path once as we need to know
+ # if any one of the local users has a principal set or not - this
+ # accounts for the entire system.
+ break
+
return ssh
@@ -86,15 +97,8 @@ def verify(ssh):
if 'rekey' in ssh and 'data' not in ssh['rekey']:
raise ConfigError('Rekey data is required!')
- if 'trusted_user_ca_key' in ssh:
- if 'ca_certificate' not in ssh['trusted_user_ca_key']:
- raise ConfigError('CA certificate is required for TrustedUserCAKey')
-
- ca_key_name = ssh['trusted_user_ca_key']['ca_certificate']
- verify_pki_ca_certificate(ssh, ca_key_name)
- pki_ca_cert = ssh['pki']['ca'][ca_key_name]
- if 'certificate' not in pki_ca_cert or not pki_ca_cert['certificate']:
- raise ConfigError(f"CA certificate '{ca_key_name}' is not valid or missing")
+ if 'trusted_user_ca' in ssh:
+ verify_pki_openssh_key(ssh, ssh['trusted_user_ca'])
verify_vrf(ssh)
return None
@@ -119,23 +123,17 @@ def generate(ssh):
syslog(LOG_INFO, 'SSH ed25519 host key not found, generating new key!')
call(f'ssh-keygen -q -N "" -t ed25519 -f {key_ed25519}')
- if 'trusted_user_ca_key' in ssh:
- ca_key_name = ssh['trusted_user_ca_key']['ca_certificate']
- pki_ca_cert = ssh['pki']['ca'][ca_key_name]
-
- loaded_ca_cert = load_certificate(pki_ca_cert['certificate'])
- loaded_ca_certs = {
- load_certificate(c['certificate'])
- for c in ssh['pki']['ca'].values()
- if 'certificate' in c
- }
-
- ca_full_chain = find_chain(loaded_ca_cert, loaded_ca_certs)
- write_file(
- trusted_user_ca_key, '\n'.join(encode_certificate(c) for c in ca_full_chain)
- )
- elif os.path.exists(trusted_user_ca_key):
- os.unlink(trusted_user_ca_key)
+ if 'trusted_user_ca' in ssh:
+ key_name = ssh['trusted_user_ca']
+ openssh_cert = ssh['pki']['openssh'][key_name]
+ loaded_ca_cert = load_openssh_public_key(openssh_cert['public']['key'],
+ openssh_cert['public']['type'])
+ tmp = encode_public_key(loaded_ca_cert, encoding='OpenSSH',
+ key_format='OpenSSH')
+ write_file(trusted_user_ca, tmp, trailing_newline=True)
+ else:
+ if os.path.exists(trusted_user_ca):
+ os.unlink(trusted_user_ca)
render(config_file, 'ssh/sshd_config.j2', ssh)
diff --git a/src/conf_mode/system_ip.py b/src/conf_mode/system_ip.py
index 7f3796168..7f8b00ceb 100755
--- a/src/conf_mode/system_ip.py
+++ b/src/conf_mode/system_ip.py
@@ -53,6 +53,11 @@ def verify(config_dict):
for protocol, protocol_options in opt['protocol'].items():
if 'route_map' in protocol_options:
verify_route_map(protocol_options['route_map'], opt)
+
+ if dict_search('import_table', opt):
+ for table_num, import_config in opt['import_table'].items():
+ if dict_search('route_map', import_config):
+ verify_route_map(import_config['route_map'], opt)
return
def generate(config_dict):
diff --git a/src/conf_mode/system_login.py b/src/conf_mode/system_login.py
index 4febb6494..22b6fcc98 100755
--- a/src/conf_mode/system_login.py
+++ b/src/conf_mode/system_login.py
@@ -26,6 +26,8 @@ from time import sleep
from vyos.base import Warning
from vyos.config import Config
+from vyos.configdep import set_dependents
+from vyos.configdep import call_dependents
from vyos.configverify import verify_vrf
from vyos.template import render
from vyos.template import is_ipv4
@@ -129,6 +131,7 @@ def get_config(config=None):
max_uid=MIN_TACACS_UID) + cli_users
login['tacacs_min_uid'] = MIN_TACACS_UID
+ set_dependents('ssh', conf)
return login
def verify(login):
@@ -345,6 +348,17 @@ def apply(login):
user_config, permission=0o600,
formater=lambda _: _.replace("&quot;", '"'),
user=user, group='users')
+
+ principals_file = f'{home_dir}/.ssh/authorized_principals'
+ if dict_search('authentication.principal', user_config):
+ render(principals_file, 'login/authorized_principals.j2',
+ user_config, permission=0o600,
+ formater=lambda _: _.replace("&quot;", '"'),
+ user=user, group='users')
+ else:
+ if os.path.exists(principals_file):
+ os.unlink(principals_file)
+
except Exception as e:
raise ConfigError(f'Adding user "{user}" raised exception: "{e}"')
@@ -361,14 +375,15 @@ def apply(login):
chown(home_dir, user=user, recursive=True)
# Generate 2FA/MFA One-Time-Pad configuration
+ google_auth_file = f'{home_dir}/.google_authenticator'
if dict_search('authentication.otp.key', user_config):
enable_otp = True
- render(f'{home_dir}/.google_authenticator', 'login/pam_otp_ga.conf.j2',
+ render(google_auth_file, 'login/pam_otp_ga.conf.j2',
user_config, permission=0o400, user=user, group='users')
else:
# delete configuration as it's not enabled for the user
- if os.path.exists(f'{home_dir}/.google_authenticator'):
- os.remove(f'{home_dir}/.google_authenticator')
+ if os.path.exists(google_auth_file):
+ os.unlink(google_auth_file)
# Lock/Unlock local user account
lock_unlock = '--unlock'
@@ -382,6 +397,22 @@ def apply(login):
# Disable user to prevent re-login
call(f'usermod -s /sbin/nologin {user}')
+ home_dir = getpwnam(user).pw_dir
+ # Remove SSH authorized keys file
+ authorized_keys_file = f'{home_dir}/.ssh/authorized_keys'
+ if os.path.exists(authorized_keys_file):
+ os.unlink(authorized_keys_file)
+
+ # Remove SSH authorized principals file
+ principals_file = f'{home_dir}/.ssh/authorized_principals'
+ if os.path.exists(principals_file):
+ os.unlink(principals_file)
+
+ # Remove Google Authenticator file
+ google_auth_file = f'{home_dir}/.google_authenticator'
+ if os.path.exists(google_auth_file):
+ os.unlink(google_auth_file)
+
# Logout user if he is still logged in
if user in list(set([tmp[0] for tmp in users()])):
print(f'{user} is logged in, forcing logout!')
@@ -420,8 +451,9 @@ def apply(login):
# Enable/disable Google authenticator
cmd('pam-auth-update --disable mfa-google-authenticator')
if enable_otp:
- cmd(f'pam-auth-update --enable mfa-google-authenticator')
+ cmd('pam-auth-update --enable mfa-google-authenticator')
+ call_dependents()
return None
diff --git a/src/conf_mode/vpn_ipsec.py b/src/conf_mode/vpn_ipsec.py
index 2754314f7..ac25cd671 100755
--- a/src/conf_mode/vpn_ipsec.py
+++ b/src/conf_mode/vpn_ipsec.py
@@ -727,7 +727,7 @@ def generate(ipsec):
for remote_prefix in remote_prefixes:
local_net = ipaddress.ip_network(local_prefix)
remote_net = ipaddress.ip_network(remote_prefix)
- if local_net.overlaps(remote_net):
+ if local_net.subnet_of(remote_net):
if passthrough is None:
passthrough = []
passthrough.append(local_prefix)
diff --git a/src/conf_mode/vpn_openconnect.py b/src/conf_mode/vpn_openconnect.py
index 42785134f..0346c7819 100755
--- a/src/conf_mode/vpn_openconnect.py
+++ b/src/conf_mode/vpn_openconnect.py
@@ -93,7 +93,7 @@ def verify(ocserv):
"radius" in ocserv["authentication"]["mode"]):
raise ConfigError('OpenConnect authentication modes are mutually-exclusive, remove either local or radius from your configuration')
if "radius" in ocserv["authentication"]["mode"]:
- if not ocserv["authentication"]['radius']['server']:
+ if 'server' not in ocserv['authentication']['radius']:
raise ConfigError('OpenConnect authentication mode radius requires at least one RADIUS server')
if "local" in ocserv["authentication"]["mode"]:
if not ocserv.get("authentication", {}).get("local_users"):
diff --git a/src/etc/opennhrp/opennhrp-script.py b/src/etc/opennhrp/opennhrp-script.py
deleted file mode 100755
index f6f6d075c..000000000
--- a/src/etc/opennhrp/opennhrp-script.py
+++ /dev/null
@@ -1,371 +0,0 @@
-#!/usr/bin/env python3
-#
-# Copyright (C) 2021-2023 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 sys
-import vyos.ipsec
-
-from json import loads
-from pathlib import Path
-
-from vyos.logger import getLogger
-from vyos.utils.process import cmd
-from vyos.utils.process import process_named_running
-
-NHRP_CONFIG: str = '/run/opennhrp/opennhrp.conf'
-
-
-def vici_get_ipsec_uniqueid(conn: str, src_nbma: str,
- dst_nbma: str) -> list[str]:
- """ Find and return IKE SAs by src nbma and dst nbma
-
- Args:
- conn (str): a connection name
- src_nbma (str): an IP address of NBMA source
- dst_nbma (str): an IP address of NBMA destination
-
- Returns:
- list: a list of IKE connections that match a criteria
- """
- if not conn or not src_nbma or not dst_nbma:
- logger.error(
- f'Incomplete input data for resolving IKE unique ids: '
- f'conn: {conn}, src_nbma: {src_nbma}, dst_nbma: {dst_nbma}')
- return []
-
- try:
- logger.info(
- f'Resolving IKE unique ids for: conn: {conn}, '
- f'src_nbma: {src_nbma}, dst_nbma: {dst_nbma}')
- list_ikeid: list[str] = []
- list_sa: list = vyos.ipsec.get_vici_sas_by_name(conn, None)
- for sa in list_sa:
- if sa[conn]['local-host'].decode('ascii') == src_nbma \
- and sa[conn]['remote-host'].decode('ascii') == dst_nbma:
- list_ikeid.append(sa[conn]['uniqueid'].decode('ascii'))
- return list_ikeid
- except Exception as err:
- logger.error(f'Unable to find unique ids for IKE: {err}')
- return []
-
-
-def vici_ike_terminate(list_ikeid: list[str]) -> bool:
- """Terminating IKE SAs by list of IKE IDs
-
- Args:
- list_ikeid (list[str]): a list of IKE ids to terminate
-
- Returns:
- bool: result of termination action
- """
- if not list:
- logger.warning('An empty list for termination was provided')
- return False
-
- try:
- vyos.ipsec.terminate_vici_ikeid_list(list_ikeid)
- return True
- except Exception as err:
- logger.error(f'Failed to terminate SA for IKE ids {list_ikeid}: {err}')
- return False
-
-
-def parse_type_ipsec(interface: str) -> tuple[str, str]:
- """Get DMVPN Type and NHRP Profile from the configuration
-
- Args:
- interface (str): a name of interface
-
- Returns:
- tuple[str, str]: `peer_type` and `profile_name`
- """
- if not interface:
- logger.error('Cannot find peer type - no input provided')
- return '', ''
-
- config_file: str = Path(NHRP_CONFIG).read_text()
- regex: str = rf'^interface {interface} #(?P<peer_type>hub|spoke) ?(?P<profile_name>[^\n]*)$'
- match = re.search(regex, config_file, re.M)
- if match:
- return match.groupdict()['peer_type'], match.groupdict()[
- 'profile_name']
- return '', ''
-
-
-def add_peer_route(nbma_src: str, nbma_dst: str, mtu: str) -> None:
- """Add a route to a NBMA peer
-
- Args:
- nbma_src (str): a local IP address
- nbma_dst (str): a remote IP address
- mtu (str): a MTU for a route
- """
- logger.info(f'Adding route from {nbma_src} to {nbma_dst} with MTU {mtu}')
- # Find routes to a peer
- route_get_cmd: str = f'sudo ip --json route get {nbma_dst} from {nbma_src}'
- try:
- route_info_data = loads(cmd(route_get_cmd))
- except Exception as err:
- logger.error(f'Unable to find a route to {nbma_dst}: {err}')
- return
-
- # Check if an output has an expected format
- if not isinstance(route_info_data, list):
- logger.error(
- f'Garbage returned from the "{route_get_cmd}" '
- f'command: {route_info_data}')
- return
-
- # Add static routes to a peer
- for route_item in route_info_data:
- route_dev = route_item.get('dev')
- route_dst = route_item.get('dst')
- route_gateway = route_item.get('gateway')
- # Prepare a command to add a route
- route_add_cmd = 'sudo ip route add'
- if route_dst:
- route_add_cmd = f'{route_add_cmd} {route_dst}'
- if route_gateway:
- route_add_cmd = f'{route_add_cmd} via {route_gateway}'
- if route_dev:
- route_add_cmd = f'{route_add_cmd} dev {route_dev}'
- route_add_cmd = f'{route_add_cmd} proto 42 mtu {mtu}'
- # Add a route
- try:
- cmd(route_add_cmd)
- except Exception as err:
- logger.error(
- f'Unable to add a route using command "{route_add_cmd}": '
- f'{err}')
-
-
-def vici_initiate(conn: str, child_sa: str, src_addr: str,
- dest_addr: str) -> bool:
- """Initiate IKE SA connection with specific peer
-
- Args:
- conn (str): an IKE connection name
- child_sa (str): a child SA profile name
- src_addr (str): NBMA local address
- dest_addr (str): NBMA address of a peer
-
- Returns:
- bool: a result of initiation command
- """
- logger.info(
- f'Trying to initiate connection. Name: {conn}, child sa: {child_sa}, '
- f'src_addr: {src_addr}, dst_addr: {dest_addr}')
- try:
- vyos.ipsec.vici_initiate(conn, child_sa, src_addr, dest_addr)
- return True
- except Exception as err:
- logger.error(f'Unable to initiate connection {err}')
- return False
-
-
-def vici_terminate(conn: str, src_addr: str, dest_addr: str) -> None:
- """Find and terminate IKE SAs by local NBMA and remote NBMA addresses
-
- Args:
- conn (str): IKE connection name
- src_addr (str): NBMA local address
- dest_addr (str): NBMA address of a peer
- """
- logger.info(
- f'Terminating IKE connection {conn} between {src_addr} '
- f'and {dest_addr}')
-
- ikeid_list: list[str] = vici_get_ipsec_uniqueid(conn, src_addr, dest_addr)
-
- if not ikeid_list:
- logger.warning(
- f'No active sessions found for IKE profile {conn}, '
- f'local NBMA {src_addr}, remote NBMA {dest_addr}')
- else:
- try:
- vyos.ipsec.terminate_vici_ikeid_list(ikeid_list)
- except Exception as err:
- logger.error(
- f'Failed to terminate SA for IKE ids {ikeid_list}: {err}')
-
-def iface_up(interface: str) -> None:
- """Proceed tunnel interface UP event
-
- Args:
- interface (str): an interface name
- """
- if not interface:
- logger.warning('No interface name provided for UP event')
-
- logger.info(f'Turning up interface {interface}')
- try:
- cmd(f'sudo ip route flush proto 42 dev {interface}')
- cmd(f'sudo ip neigh flush dev {interface}')
- except Exception as err:
- logger.error(
- f'Unable to flush route on interface "{interface}": {err}')
-
-
-def peer_up(dmvpn_type: str, conn: str) -> None:
- """Proceed NHRP peer UP event
-
- Args:
- dmvpn_type (str): a type of peer
- conn (str): an IKE profile name
- """
- logger.info(f'Peer UP event for {dmvpn_type} using IKE profile {conn}')
- src_nbma = os.getenv('NHRP_SRCNBMA')
- dest_nbma = os.getenv('NHRP_DESTNBMA')
- dest_mtu = os.getenv('NHRP_DESTMTU')
-
- if not src_nbma or not dest_nbma:
- logger.error(
- f'Can not get NHRP NBMA addresses: local {src_nbma}, '
- f'remote {dest_nbma}')
- return
-
- logger.info(f'NBMA addresses: local {src_nbma}, remote {dest_nbma}')
- if dest_mtu:
- add_peer_route(src_nbma, dest_nbma, dest_mtu)
- if conn and dmvpn_type == 'spoke' and process_named_running('charon'):
- vici_terminate(conn, src_nbma, dest_nbma)
- vici_initiate(conn, 'dmvpn', src_nbma, dest_nbma)
-
-
-def peer_down(dmvpn_type: str, conn: str) -> None:
- """Proceed NHRP peer DOWN event
-
- Args:
- dmvpn_type (str): a type of peer
- conn (str): an IKE profile name
- """
- logger.info(f'Peer DOWN event for {dmvpn_type} using IKE profile {conn}')
-
- src_nbma = os.getenv('NHRP_SRCNBMA')
- dest_nbma = os.getenv('NHRP_DESTNBMA')
-
- if not src_nbma or not dest_nbma:
- logger.error(
- f'Can not get NHRP NBMA addresses: local {src_nbma}, '
- f'remote {dest_nbma}')
- return
-
- logger.info(f'NBMA addresses: local {src_nbma}, remote {dest_nbma}')
- if conn and dmvpn_type == 'spoke' and process_named_running('charon'):
- vici_terminate(conn, src_nbma, dest_nbma)
- try:
- cmd(f'sudo ip route del {dest_nbma} src {src_nbma} proto 42')
- except Exception as err:
- logger.error(
- f'Unable to del route from {src_nbma} to {dest_nbma}: {err}')
-
-
-def route_up(interface: str) -> None:
- """Proceed NHRP route UP event
-
- Args:
- interface (str): an interface name
- """
- logger.info(f'Route UP event for interface {interface}')
-
- dest_addr = os.getenv('NHRP_DESTADDR')
- dest_prefix = os.getenv('NHRP_DESTPREFIX')
- next_hop = os.getenv('NHRP_NEXTHOP')
-
- if not dest_addr or not dest_prefix or not next_hop:
- logger.error(
- f'Can not get route details: dest_addr {dest_addr}, '
- f'dest_prefix {dest_prefix}, next_hop {next_hop}')
- return
-
- logger.info(
- f'Route details: dest_addr {dest_addr}, dest_prefix {dest_prefix}, '
- f'next_hop {next_hop}')
-
- try:
- cmd(f'sudo ip route replace {dest_addr}/{dest_prefix} proto 42 \
- via {next_hop} dev {interface}')
- cmd('sudo ip route flush cache')
- except Exception as err:
- logger.error(
- f'Unable replace or flush route to {dest_addr}/{dest_prefix} '
- f'via {next_hop} dev {interface}: {err}')
-
-
-def route_down(interface: str) -> None:
- """Proceed NHRP route DOWN event
-
- Args:
- interface (str): an interface name
- """
- logger.info(f'Route DOWN event for interface {interface}')
-
- dest_addr = os.getenv('NHRP_DESTADDR')
- dest_prefix = os.getenv('NHRP_DESTPREFIX')
-
- if not dest_addr or not dest_prefix:
- logger.error(
- f'Can not get route details: dest_addr {dest_addr}, '
- f'dest_prefix {dest_prefix}')
- return
-
- logger.info(
- f'Route details: dest_addr {dest_addr}, dest_prefix {dest_prefix}')
- try:
- cmd(f'sudo ip route del {dest_addr}/{dest_prefix} proto 42')
- cmd('sudo ip route flush cache')
- except Exception as err:
- logger.error(
- f'Unable delete or flush route to {dest_addr}/{dest_prefix}: '
- f'{err}')
-
-
-if __name__ == '__main__':
- logger = getLogger('opennhrp-script', syslog=True)
- logger.debug(
- f'Running script with arguments: {sys.argv}, '
- f'environment: {os.environ}')
-
- action = sys.argv[1]
- interface = os.getenv('NHRP_INTERFACE')
-
- if not interface:
- logger.error('Can not get NHRP interface name')
- sys.exit(1)
-
- dmvpn_type, profile_name = parse_type_ipsec(interface)
- if not dmvpn_type:
- logger.info(f'Interface {interface} is not NHRP tunnel')
- sys.exit()
-
- dmvpn_conn: str = ''
- if profile_name:
- dmvpn_conn: str = f'dmvpn-{profile_name}-{interface}'
- if action == 'interface-up':
- iface_up(interface)
- elif action == 'peer-register':
- pass
- elif action == 'peer-up':
- peer_up(dmvpn_type, dmvpn_conn)
- elif action == 'peer-down':
- peer_down(dmvpn_type, dmvpn_conn)
- elif action == 'route-up':
- route_up(interface)
- elif action == 'route-down':
- route_down(interface)
-
- sys.exit()
diff --git a/src/helpers/run-config-migration.py b/src/helpers/run-config-migration.py
index e6ce97363..8e0d56150 100755
--- a/src/helpers/run-config-migration.py
+++ b/src/helpers/run-config-migration.py
@@ -19,6 +19,7 @@ import sys
import time
from argparse import ArgumentParser
from shutil import copyfile
+from vyos.utils.file import read_file
from vyos.migrate import ConfigMigrate
from vyos.migrate import ConfigMigrateError
@@ -76,3 +77,9 @@ except ConfigMigrateError as e:
if backup is not None and not config_migrate.config_modified:
os.unlink(backup)
+
+# T1771: add knob on Kernel command-line to simulate failed config migrator run
+# used to test if the automatic image reboot works.
+kernel_cmdline = read_file('/proc/cmdline')
+if 'vyos-fail-migration' in kernel_cmdline.split():
+ sys.exit(1)
diff --git a/src/helpers/set_vyconf_backend.py b/src/helpers/set_vyconf_backend.py
new file mode 100755
index 000000000..6747e51c3
--- /dev/null
+++ b/src/helpers/set_vyconf_backend.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2025 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/>.
+#
+#
+
+# N.B. only for use within testing framework; explicit invocation will leave
+# system in inconsistent state.
+
+from argparse import ArgumentParser
+
+from vyos.utils.backend import set_vyconf_backend
+
+
+parser = ArgumentParser()
+parser.add_argument('--disable', action='store_true',
+ help='enable/disable vyconf backend')
+parser.add_argument('--no-prompt', action='store_true',
+ help='confirm without prompt')
+
+args = parser.parse_args()
+
+match args.disable:
+ case False:
+ set_vyconf_backend(True, no_prompt=args.no_prompt)
+ case True:
+ set_vyconf_backend(False, no_prompt=args.no_prompt)
diff --git a/src/helpers/teardown-config-session.py b/src/helpers/teardown-config-session.py
new file mode 100755
index 000000000..c94876924
--- /dev/null
+++ b/src/helpers/teardown-config-session.py
@@ -0,0 +1,30 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2025 VyOS maintainers and contributors
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 or later as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+#
+
+import sys
+import os
+
+from vyos.vyconf_session import VyconfSession
+
+if len(sys.argv) < 2:
+ sys.exit('session pid is required')
+
+pid = sys.argv[1]
+
+vc = VyconfSession(pid=pid)
+vc.teardown()
diff --git a/src/init/vyos-router b/src/init/vyos-router
index 6f1d386d6..5c88c0665 100755
--- a/src/init/vyos-router
+++ b/src/init/vyos-router
@@ -67,37 +67,50 @@ disabled () {
grep -q -w no-vyos-$1 /proc/cmdline
}
+motd_helper() {
+ MOTD_DIR="/run/motd.d"
+ MOTD_FILE="${MOTD_DIR}/99-vyos-update-failed"
+
+ if [[ ! -d ${MOTD_DIR} ]]; then
+ mkdir -p ${MOTD_DIR}
+ fi
+
+ echo "" > ${MOTD_FILE}
+ echo "WARNING: Image update to \"$1\" failed." >> ${MOTD_FILE}
+ echo "Please check the logs:" >> ${MOTD_FILE}
+ echo "/usr/lib/live/mount/persistence/boot/$1/rw/var/log" >> ${MOTD_FILE}
+ echo "Message is cleared on next reboot!" >> ${MOTD_FILE}
+ echo "" >> ${MOTD_FILE}
+}
+
# Load encrypted config volume
mount_encrypted_config() {
persist_path=$(/opt/vyatta/sbin/vyos-persistpath)
if [ $? == 0 ]; then
if [ -e $persist_path/boot ]; then
image_name=$(cat /proc/cmdline | sed -e s+^.*vyos-union=/boot/++ | sed -e 's/ .*$//')
-
if [ -z "$image_name" ]; then
- return
+ return 0
fi
if [ ! -f $persist_path/luks/$image_name ]; then
- return
+ return 0
fi
vyos_tpm_key=$(python3 -c 'from vyos.tpm import read_tpm_key; print(read_tpm_key().decode())' 2>/dev/null)
-
if [ $? -ne 0 ]; then
echo "ERROR: Failed to fetch encryption key from TPM. Encrypted config volume has not been mounted"
echo "Use 'encryption load' to load volume with recovery key"
echo "or 'encryption disable' to decrypt volume with recovery key"
- return
+ return 1
fi
echo $vyos_tpm_key | tr -d '\r\n' | cryptsetup open $persist_path/luks/$image_name vyos_config --key-file=-
-
if [ $? -ne 0 ]; then
echo "ERROR: Failed to decrypt config volume. Encrypted config volume has not been mounted"
echo "Use 'encryption load' to load volume with recovery key"
echo "or 'encryption disable' to decrypt volume with recovery key"
- return
+ return 1
fi
mount /dev/mapper/vyos_config /config
@@ -106,6 +119,7 @@ mount_encrypted_config() {
echo "Mounted encrypted config volume"
fi
fi
+ return 0
}
unmount_encrypted_config() {
@@ -160,11 +174,16 @@ migrate_bootfile ()
if [ -x $vyos_libexec_dir/run-config-migration.py ]; then
log_progress_msg migrate
sg ${GROUP} -c "$vyos_libexec_dir/run-config-migration.py $BOOTFILE"
+ STATUS=$?
+ if [[ "$STATUS" != "0" ]]; then
+ return 1
+ fi
# update vyconf copy after migration
if [ -d $VYCONF_CONFIG_DIR ] ; then
cp -f $BOOTFILE $VYCONF_CONFIG_DIR/config.boot
fi
fi
+ return 0
}
# configure system-specific settings
@@ -187,8 +206,13 @@ load_bootfile ()
fi
if [ -x $vyos_libexec_dir/vyos-boot-config-loader.py ]; then
sg ${GROUP} -c "$vyos_libexec_dir/vyos-boot-config-loader.py $BOOTFILE"
+ STATUS=$?
+ if [[ "$STATUS" != "0" ]]; then
+ return 1
+ fi
fi
)
+ return 0
}
# restore if missing pre-config script
@@ -289,10 +313,10 @@ clear_or_override_config_files ()
keepalived/keepalived.conf cron.d/vyos-crontab \
ipvsadm.rules default/ipvsadm resolv.conf
do
- if [ -s /etc/$conf ] ; then
- empty /etc/$conf
- chmod 0644 /etc/$conf
- fi
+ if [ -s /etc/$conf ] ; then
+ empty /etc/$conf
+ chmod 0644 /etc/$conf
+ fi
done
}
@@ -417,6 +441,8 @@ gen_duid ()
start ()
{
+ log_success_msg "Starting VyOS router"
+
# reset and clean config files
security_reset || log_failure_msg "security reset failed"
@@ -482,7 +508,7 @@ start ()
# enable some debugging before loading the configuration
if grep -q vyos-debug /proc/cmdline; then
- log_action_begin_msg "Enable runtime debugging options"
+ log_success_msg "Enable runtime debugging options"
FRR_DEBUG=$(python3 -c "from vyos.defaults import frr_debug_enable; print(frr_debug_enable)")
touch $FRR_DEBUG
touch /tmp/vyos.container.debug
@@ -509,7 +535,7 @@ start ()
&& chgrp ${GROUP} ${vyatta_configdir}
log_action_end_msg $?
- mount_encrypted_config
+ mount_encrypted_config || overall_status=1
# T5239: early read of system hostname as this value is read-only once during
# FRR initialisation
@@ -525,8 +551,7 @@ start ()
cleanup_post_commit_hooks
- log_daemon_msg "Starting VyOS router"
- disabled migrate || migrate_bootfile
+ disabled migrate || migrate_bootfile || overall_status=1
restore_if_missing_preconfig_script
@@ -534,27 +559,66 @@ start ()
run_postupgrade_script
- update_interface_config
+ update_interface_config || overall_status=1
- disabled system_config || system_config
+ disabled system_config || system_config || overall_status=1
systemctl start vyconfd.service
for s in ${subinit[@]} ; do
- if ! disabled $s; then
- log_progress_msg $s
- if ! ${vyatta_sbindir}/${s}.init start
- then log_failure_msg
- exit 1
+ if ! disabled $s; then
+ log_progress_msg $s
+ if ! ${vyatta_sbindir}/${s}.init start
+ then log_failure_msg
+ exit 1
+ fi
fi
- fi
done
bind_mount_boot
- disabled configure || load_bootfile
+ disabled configure || load_bootfile || overall_status=1
log_end_msg $?
+ FIRST_BOOT_FILE="/config/first_boot"
+ UPDATE_FAILED_BOOT_FILE="/config/update_failed"
+ AUTOMATIC_REBOOT_TMO=$(${vyos_libexec_dir}/read-saved-value.py --path "system option reboot-on-upgrade-failure")
+ # Image upgrade failed - get previous image name, re-set it as default image
+ # and perform an automatic reboot. Automatic reboot timeout can be set via CLI
+ if [[ -n $AUTOMATIC_REBOOT_TMO ]] && [[ -f ${FIRST_BOOT_FILE} ]] && [[ ${overall_status} -ne 0 ]]; then
+ previous_image=$(jq -r '.previous_image' ${FIRST_BOOT_FILE})
+
+ # If the image update failed, we need to inform the image we will revert
+ # to about this
+ running_image=$(${vyos_op_scripts_dir}/image_info.py show_images_current --raw | jq -r '.image_running')
+ echo "{\"failed_image_update\": \"${running_image}\"}" \
+ > /usr/lib/live/mount/persistence/boot/${previous_image}/rw/${UPDATE_FAILED_BOOT_FILE}
+
+ ${vyos_op_scripts_dir}/image_manager.py --action set --image-name "${previous_image}" >/dev/null 2>&1
+ motd_helper "${running_image}"
+
+ log_daemon_msg "Booting failed, reverting to previous image"
+ log_progress_msg ${previous_image}
+ log_end_msg 0
+ log_daemon_msg "Automatic reboot in ${AUTOMATIC_REBOOT_TMO} minutes"
+ sync ; shutdown --reboot --no-wall ${AUTOMATIC_REBOOT_TMO} >/dev/null 2>&1
+ log_progress_msg "Use \"reboot cancel\" to cancel"
+ log_end_msg 0
+ fi
+ # After image upgrade failure and once booted into the previous working
+ # image, inform the user via MOTD about the failure
+ if [[ -n $AUTOMATIC_REBOOT_TMO ]] && [[ -f ${UPDATE_FAILED_BOOT_FILE} ]] ; then
+ failed_image_update=$(jq -r '.failed_image_update' ${UPDATE_FAILED_BOOT_FILE})
+ motd_helper "${failed_image_update}"
+ fi
+ # Clear marker files used by automatic reboot on image upgrade mechanism
+ if [[ -f ${FIRST_BOOT_FILE} ]]; then
+ rm -f ${FIRST_BOOT_FILE}
+ fi
+ if [[ -f ${UPDATE_FAILED_BOOT_FILE} ]] ; then
+ rm -f ${UPDATE_FAILED_BOOT_FILE}
+ fi
+
telinit q
chmod g-w,o-w /
diff --git a/src/op_mode/image_info.py b/src/op_mode/image_info.py
index 56aefcd6e..0ec930543 100755
--- a/src/op_mode/image_info.py
+++ b/src/op_mode/image_info.py
@@ -72,6 +72,14 @@ def _format_show_images_details(
return tabulated
+def show_images_current(raw: bool) -> Union[image.BootDetails, str]:
+
+ images_summary = show_images_summary(raw=True)
+ if raw:
+ return {'image_running' : images_summary['image_running']}
+ else:
+ return images_summary['image_running']
+
def show_images_summary(raw: bool) -> Union[image.BootDetails, str]:
images_available: list[str] = grub.version_list()
diff --git a/src/op_mode/image_installer.py b/src/op_mode/image_installer.py
index ac5a84419..27371a18f 100755
--- a/src/op_mode/image_installer.py
+++ b/src/op_mode/image_installer.py
@@ -27,6 +27,7 @@ from os import readlink
from os import getpid
from os import getppid
from json import loads
+from json import dumps
from typing import Union
from urllib.parse import urlparse
from passlib.hosts import linux_context
@@ -54,6 +55,7 @@ from vyos.utils.dict import dict_search
from vyos.utils.io import ask_input, ask_yes_no, select_entry
from vyos.utils.file import chmod_2775
from vyos.utils.file import read_file
+from vyos.utils.file import write_file
from vyos.utils.process import cmd, run, rc_cmd
from vyos.version import get_version_data
@@ -1040,6 +1042,12 @@ def add_image(image_path: str, vrf: str = None, username: str = '',
chmod_2775(target_config_dir)
copytree('/opt/vyatta/etc/config/', target_config_dir, symlinks=True,
copy_function=copy_preserve_owner, dirs_exist_ok=True)
+
+ # Record information from which image we upgraded to the new one.
+ # This can be used for a future automatic rollback into the old image.
+ tmp = {'previous_image' : image.get_running_image()}
+ write_file(f'{target_config_dir}/first_boot', dumps(tmp))
+
else:
Path(target_config_dir).mkdir(parents=True)
chown(target_config_dir, group='vyattacfg')
diff --git a/src/services/api/rest/models.py b/src/services/api/rest/models.py
index dda50010f..47c7a65b3 100644
--- a/src/services/api/rest/models.py
+++ b/src/services/api/rest/models.py
@@ -134,13 +134,15 @@ class RetrieveModel(ApiModel):
class ConfigFileModel(ApiModel):
op: StrictStr
file: StrictStr = None
+ string: StrictStr = None
class Config:
json_schema_extra = {
'example': {
'key': 'id_key',
- 'op': 'save | load',
+ 'op': 'save | load | merge',
'file': 'filename',
+ 'string': 'config_string'
}
}
@@ -251,6 +253,20 @@ class RebootModel(ApiModel):
}
+class RenewModel(ApiModel):
+ op: StrictStr
+ path: List[StrictStr]
+
+ class Config:
+ json_schema_extra = {
+ 'example': {
+ 'key': 'id_key',
+ 'op': 'renew',
+ 'path': ['op', 'mode', 'path'],
+ }
+ }
+
+
class ResetModel(ApiModel):
op: StrictStr
path: List[StrictStr]
diff --git a/src/services/api/rest/routers.py b/src/services/api/rest/routers.py
index e52c77fda..4866ec5d8 100644
--- a/src/services/api/rest/routers.py
+++ b/src/services/api/rest/routers.py
@@ -66,6 +66,7 @@ from .models import GenerateModel
from .models import ShowModel
from .models import RebootModel
from .models import ResetModel
+from .models import RenewModel
from .models import ImportPkiModel
from .models import PoweroffModel
from .models import TracerouteModel
@@ -507,13 +508,21 @@ def config_file_op(data: ConfigFileModel, background_tasks: BackgroundTasks):
else:
path = '/config/config.boot'
msg = session.save_config(path)
- elif op == 'load':
+ elif op in ('load', 'merge'):
if data.file:
path = data.file
+ elif data.string:
+ path = '/tmp/config.file'
+ with open(path, 'w') as f:
+ f.write(data.string)
else:
- return error(400, 'Missing required field "file"')
+ return error(400, 'Missing required field "file | string"')
- session.migrate_and_load_config(path)
+ match op:
+ case 'load':
+ session.migrate_and_load_config(path)
+ case 'merge':
+ session.merge_config(path)
config = Config(session_env=env)
d = get_config_diff(config)
@@ -657,6 +666,26 @@ def reboot_op(data: RebootModel):
return success(res)
+@router.post('/renew')
+def renew_op(data: RenewModel):
+ state = SessionState()
+ session = state.session
+
+ op = data.op
+ path = data.path
+
+ try:
+ if op == 'renew':
+ res = session.renew(path)
+ else:
+ return error(400, f"'{op}' is not a valid operation")
+ except ConfigSessionError as e:
+ return error(400, str(e))
+ except Exception:
+ LOG.critical(traceback.format_exc())
+ return error(500, 'An internal error occured. Check the logs for details.')
+
+ return success(res)
@router.post('/reset')
def reset_op(data: ResetModel):
diff --git a/src/systemd/opennhrp.service b/src/systemd/opennhrp.service
deleted file mode 100644
index c9a44de29..000000000
--- a/src/systemd/opennhrp.service
+++ /dev/null
@@ -1,13 +0,0 @@
-[Unit]
-Description=OpenNHRP
-After=vyos-router.service
-ConditionPathExists=/run/opennhrp/opennhrp.conf
-StartLimitIntervalSec=0
-
-[Service]
-Type=forking
-ExecStart=/usr/sbin/opennhrp -d -v -a /run/opennhrp.socket -c /run/opennhrp/opennhrp.conf -s /etc/opennhrp/opennhrp-script.py -p /run/opennhrp/opennhrp.pid
-ExecReload=/usr/bin/kill -HUP $MAINPID
-PIDFile=/run/opennhrp/opennhrp.pid
-Restart=on-failure
-RestartSec=20
diff --git a/src/systemd/vyconfd.service b/src/systemd/vyconfd.service
index ab2280263..d23ca2202 100644
--- a/src/systemd/vyconfd.service
+++ b/src/systemd/vyconfd.service
@@ -8,7 +8,7 @@ DefaultDependencies=no
After=systemd-remount-fs.service
[Service]
-ExecStart=/usr/libexec/vyos/vyconf/vyconfd --log-file /var/run/log/vyconfd.log
+ExecStart=/usr/libexec/vyos/vyconf/vyconfd --log-file /var/run/log/vyconfd.log --legacy-config-path
Type=exec
SyslogIdentifier=vyconfd
SyslogFacility=daemon
diff --git a/src/tests/test_template.py b/src/tests/test_template.py
index 7cae867a0..4660c0038 100644
--- a/src/tests/test_template.py
+++ b/src/tests/test_template.py
@@ -192,10 +192,15 @@ class TestVyOSTemplate(TestCase):
self.assertIn(IKEv2_DEFAULT, ','.join(ciphers))
def test_get_default_port(self):
+ from vyos.defaults import config_files
from vyos.defaults import internal_ports
with self.assertRaises(RuntimeError):
+ vyos.template.get_default_config_file('UNKNOWN')
+ with self.assertRaises(RuntimeError):
vyos.template.get_default_port('UNKNOWN')
+ self.assertEqual(vyos.template.get_default_config_file('sshd_user_ca'),
+ config_files['sshd_user_ca'])
self.assertEqual(vyos.template.get_default_port('certbot_haproxy'),
internal_ports['certbot_haproxy'])
diff --git a/src/validators/bgp-large-community-list b/src/validators/bgp-large-community-list
index 9ba5b27eb..75276630c 100755
--- a/src/validators/bgp-large-community-list
+++ b/src/validators/bgp-large-community-list
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
#
-# Copyright (C) 2021-2023 VyOS maintainers and contributors
+# Copyright (C) 2021-2025 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
@@ -17,18 +17,27 @@
import re
import sys
-pattern = '(.*):(.*):(.*)'
-allowedChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '+', '*', '?', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\', ':', '-' }
+allowedChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '+', '*', '?', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\', ':', '-', '_', ' ' }
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit(1)
- value = sys.argv[1].split(':')
- if not len(value) == 3:
+ value = sys.argv[1]
+
+ # Require at least one well-formed large-community tuple in the pattern.
+ tmp = value.split(':')
+ if len(tmp) < 3:
+ sys.exit(1)
+
+ # Simple guard against invalid community & 1003.2 pattern chars
+ if not set(value).issubset(allowedChars):
sys.exit(1)
- if not (re.match(pattern, sys.argv[1]) and set(sys.argv[1]).issubset(allowedChars)):
+ # Don't feed FRR badly formed regex
+ try:
+ re.compile(value)
+ except re.error:
sys.exit(1)
sys.exit(0)