diff options
-rw-r--r-- | data/templates/ipsec/swanctl/l2tp.tmpl | 2 | ||||
-rw-r--r-- | data/templates/ipsec/swanctl/peer.tmpl | 10 | ||||
-rw-r--r-- | data/templates/ipsec/swanctl/profile.tmpl | 2 | ||||
-rw-r--r-- | data/templates/ipsec/swanctl/remote_access.tmpl | 2 | ||||
-rw-r--r-- | data/templates/squid/squid.conf.tmpl | 8 | ||||
-rw-r--r-- | data/templates/squid/squidGuard.conf.tmpl | 45 | ||||
-rw-r--r-- | interface-definitions/include/source-address-ipv4.xml.i | 2 | ||||
-rw-r--r-- | interface-definitions/service_webproxy.xml.in | 1 | ||||
-rw-r--r-- | interface-definitions/vpn_ipsec.xml.in | 2 | ||||
-rw-r--r-- | op-mode-definitions/pki.xml.in | 71 | ||||
-rw-r--r-- | python/vyos/airbag.py | 8 | ||||
-rw-r--r-- | python/vyos/template.py | 11 | ||||
-rwxr-xr-x | smoketest/scripts/cli/test_service_webproxy.py | 6 | ||||
-rwxr-xr-x | src/conf_mode/service_webproxy.py | 3 | ||||
-rwxr-xr-x | src/conf_mode/vpn_ipsec.py | 3 | ||||
-rwxr-xr-x | src/op_mode/pki.py | 38 | ||||
-rwxr-xr-x | src/op_mode/restart_frr.py | 131 | ||||
-rwxr-xr-x | src/op_mode/show_version.py | 4 | ||||
-rw-r--r-- | src/systemd/dhcp6c@.service | 2 |
19 files changed, 194 insertions, 157 deletions
diff --git a/data/templates/ipsec/swanctl/l2tp.tmpl b/data/templates/ipsec/swanctl/l2tp.tmpl index 2df5c2a4d..4cd1b4af3 100644 --- a/data/templates/ipsec/swanctl/l2tp.tmpl +++ b/data/templates/ipsec/swanctl/l2tp.tmpl @@ -20,7 +20,7 @@ children { l2tp_remote_access_esp { mode = transport - esp_proposals = {{ l2tp_esp | get_esp_ike_cipher | join(',') if l2tp_esp else l2tp_esp_default }} + esp_proposals = {{ l2tp_esp | get_esp_ike_cipher(l2tp_ike) | join(',') if l2tp_esp else l2tp_esp_default }} life_time = {{ l2tp_esp.lifetime if l2tp_esp else l2tp.lifetime }}s local_ts = dynamic[/1701] remote_ts = dynamic diff --git a/data/templates/ipsec/swanctl/peer.tmpl b/data/templates/ipsec/swanctl/peer.tmpl index 019f9e0d7..98c09436c 100644 --- a/data/templates/ipsec/swanctl/peer.tmpl +++ b/data/templates/ipsec/swanctl/peer.tmpl @@ -31,7 +31,7 @@ encap = yes {% endif %} local { -{% if peer_conf.authentication is defined and peer_conf.authentication.id is defined and peer_conf.authentication.use_x509_id is not defined %} +{% if peer_conf.authentication is defined and peer_conf.authentication.id is defined and peer_conf.authentication.id is not none %} id = "{{ peer_conf.authentication.id }}" {% endif %} auth = {{ 'psk' if peer_conf.authentication.mode == 'pre-shared-secret' else 'pubkey' }} @@ -42,9 +42,9 @@ {% endif %} } remote { -{% if peer_conf.authentication.remote_id is defined %} +{% if peer_conf.authentication is defined and peer_conf.authentication.remote_id is defined and peer_conf.authentication.remote_id is not none %} id = "{{ peer_conf.authentication.remote_id }}" -{% elif peer[0:1] == '@' %} +{% else %} id = "{{ peer }}" {% endif %} auth = {{ 'psk' if peer_conf.authentication.mode == 'pre-shared-secret' else 'pubkey' }} @@ -56,7 +56,7 @@ {% if peer_conf.vti is defined and peer_conf.vti.bind is defined and peer_conf.tunnel is not defined %} {% set vti_esp = esp_group[ peer_conf.vti.esp_group ] if peer_conf.vti.esp_group is defined else esp_group[ peer_conf.default_esp_group ] %} peer_{{ name }}_vti { - esp_proposals = {{ vti_esp | get_esp_ike_cipher | join(',') }} + esp_proposals = {{ vti_esp | get_esp_ike_cipher(ike) | join(',') }} life_time = {{ vti_esp.lifetime }}s local_ts = 0.0.0.0/0,::/0 remote_ts = 0.0.0.0/0,::/0 @@ -87,7 +87,7 @@ {% set remote_port = tunnel_conf.remote.port if tunnel_conf.remote is defined and tunnel_conf.remote.port is defined else '' %} {% set remote_suffix = '[{0}/{1}]'.format(proto, remote_port) if proto or remote_port else '' %} peer_{{ name }}_tunnel_{{ tunnel_id }} { - esp_proposals = {{ tunnel_esp | get_esp_ike_cipher | join(',') }} + esp_proposals = {{ tunnel_esp | get_esp_ike_cipher(ike) | join(',') }} life_time = {{ tunnel_esp.lifetime }}s {% if tunnel_esp.mode is not defined or tunnel_esp.mode == 'tunnel' %} {% if tunnel_conf.local is defined and tunnel_conf.local.prefix is defined %} diff --git a/data/templates/ipsec/swanctl/profile.tmpl b/data/templates/ipsec/swanctl/profile.tmpl index 66bcaa776..948dd8f87 100644 --- a/data/templates/ipsec/swanctl/profile.tmpl +++ b/data/templates/ipsec/swanctl/profile.tmpl @@ -19,7 +19,7 @@ {% endif %} children { dmvpn { - esp_proposals = {{ esp | get_esp_ike_cipher | join(',') }} + esp_proposals = {{ esp | get_esp_ike_cipher(ike) | join(',') }} rekey_time = {{ esp.lifetime }}s rand_time = 540s local_ts = dynamic[gre] diff --git a/data/templates/ipsec/swanctl/remote_access.tmpl b/data/templates/ipsec/swanctl/remote_access.tmpl index 4fdc2a276..6354c60b1 100644 --- a/data/templates/ipsec/swanctl/remote_access.tmpl +++ b/data/templates/ipsec/swanctl/remote_access.tmpl @@ -35,7 +35,7 @@ } children { ikev2-vpn { - esp_proposals = {{ esp | get_esp_ike_cipher | join(',') }} + esp_proposals = {{ esp | get_esp_ike_cipher(ike) | join(',') }} rekey_time = {{ esp.lifetime }}s rand_time = 540s dpd_action = clear diff --git a/data/templates/squid/squid.conf.tmpl b/data/templates/squid/squid.conf.tmpl index 8754e762d..80826fc75 100644 --- a/data/templates/squid/squid.conf.tmpl +++ b/data/templates/squid/squid.conf.tmpl @@ -1,7 +1,5 @@ ### generated by service_webproxy.py ### -acl localhost src 127.0.0.1/32 -acl to_localhost dst 127.0.0.0/8 acl net src all acl SSL_ports port 443 acl Safe_ports port 80 # http @@ -101,9 +99,9 @@ forwarded_for off {# SquidGuard #} {% if url_filtering is defined and url_filtering.disable is not defined %} {% if url_filtering.squidguard is defined and url_filtering.squidguard is not none %} -redirect_program /usr/bin/squidGuard -c {{ squidguard_conf }} -redirect_children 8 -redirector_bypass on +url_rewrite_program /usr/bin/squidGuard -c {{ squidguard_conf }} +url_rewrite_children 8 +url_rewrite_bypass on {% endif %} {% endif %} diff --git a/data/templates/squid/squidGuard.conf.tmpl b/data/templates/squid/squidGuard.conf.tmpl index f530d1072..c59dc901e 100644 --- a/data/templates/squid/squidGuard.conf.tmpl +++ b/data/templates/squid/squidGuard.conf.tmpl @@ -75,17 +75,50 @@ dest local-block-keyword-default { {% set acl.value = acl.value + ' ' + category + '-default' %} {% endfor %} {% endif %} +{% if sg_config.source_group is defined and sg_config.source_group is not none %} +{% for sgroup, sg_config in sg_config.source_group.items() %} +{% if sg_config.address is defined and sg_config.address is not none %} +src {{ sgroup }} { +{% for address in sg_config.address %} + ip {{ address }} +{% endfor %} +} + +{% endif %} +{% endfor %} +{% endif %} +{% if sg_config.rule is defined and sg_config.rule is not none %} +{% for rule, rule_config in sg_config.rule.items() %} +{% for b_category in rule_config.block_category%} +dest {{ b_category }} { + domainlist {{ b_category }}/domains + urllist {{ b_category }}/urls +} +{% endfor %} + +{% endfor %} +{% endif %} acl { - default { +{% if sg_config.rule is defined and sg_config.rule is not none %} +{% for rule, rule_config in sg_config.rule.items() %} + {{ rule_config.source_group }} { +{% for b_category in rule_config.block_category%} + pass local-ok-1 !in-addr !{{ b_category }} all +{% endfor %} + } +{% endfor %} +{% endif %} + + default { {% if sg_config.enable_safe_search is defined %} - rewrite safesearch + rewrite safesearch {% endif %} - pass {{ acl.value }} {{ 'none' if sg_config.default_action is defined and sg_config.default_action == 'block' else 'allow' }} - redirect 302:http://{{ sg_config.redirect_url }} + pass {{ acl.value }} {{ 'none' if sg_config.default_action is defined and sg_config.default_action == 'block' else 'allow' }} + redirect 302:http://{{ sg_config.redirect_url }} {% if sg_config.log is defined and sg_config.log is not none %} - log blacklist.log + log blacklist.log {% endif %} - } + } } {% endif %} {% endif %} diff --git a/interface-definitions/include/source-address-ipv4.xml.i b/interface-definitions/include/source-address-ipv4.xml.i index 86235df61..052678113 100644 --- a/interface-definitions/include/source-address-ipv4.xml.i +++ b/interface-definitions/include/source-address-ipv4.xml.i @@ -1,7 +1,7 @@ <!-- include start from source-address-ipv4.xml.i --> <leafNode name="source-address"> <properties> - <help>IPv4 source address used to initiiate connection</help> + <help>IPv4 source address used to initiate connection</help> <completionHelp> <script>${vyos_completion_dir}/list_local_ips.sh --ipv4</script> </completionHelp> diff --git a/interface-definitions/service_webproxy.xml.in b/interface-definitions/service_webproxy.xml.in index 64747420b..d61a95690 100644 --- a/interface-definitions/service_webproxy.xml.in +++ b/interface-definitions/service_webproxy.xml.in @@ -504,6 +504,7 @@ <validator name="ipv4-prefix"/> <validator name="ipv4-range"/> </constraint> + <multi/> </properties> </leafNode> <leafNode name="description"> diff --git a/interface-definitions/vpn_ipsec.xml.in b/interface-definitions/vpn_ipsec.xml.in index ed4941efc..4120232ea 100644 --- a/interface-definitions/vpn_ipsec.xml.in +++ b/interface-definitions/vpn_ipsec.xml.in @@ -83,7 +83,7 @@ </completionHelp> <valueHelp> <format>enable</format> - <description>Use Diffie-Hellman group 2 (modp1024) - default</description> + <description>Inherit Diffie-Hellman group from IKE group - default</description> </valueHelp> <valueHelp> <format>dh-group1</format> diff --git a/op-mode-definitions/pki.xml.in b/op-mode-definitions/pki.xml.in index 6b9b0d3f6..a1c55dcf4 100644 --- a/op-mode-definitions/pki.xml.in +++ b/op-mode-definitions/pki.xml.in @@ -353,60 +353,45 @@ <children> <node name="pki"> <properties> - <help>Show PKI certificates</help> + <help>Show PKI x509 certificates</help> </properties> <children> - <node name="ca"> + <leafNode name="ca"> <properties> - <help>Show CA certificates</help> + <help>Show x509 CA certificates</help> </properties> - <children> - <leafNode name="name"> - <properties> - <help>Show CA certificate by name</help> - <completionHelp> - <path>pki ca</path> - </completionHelp> - </properties> - <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --ca "$5"</command> - </leafNode> - </children> <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --ca "all"</command> - </node> - <node name="certificate"> + </leafNode> + <tagNode name="ca"> <properties> - <help>Show certificates</help> + <help>Show x509 CA certificate by name</help> + <completionHelp> + <path>pki ca</path> + </completionHelp> + </properties> + <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --ca "$4"</command> + </tagNode> + <leafNode name="certificate"> + <properties> + <help>Show x509 certificates</help> </properties> - <children> - <leafNode name="name"> - <properties> - <help>Show certificate by name</help> - <completionHelp> - <path>pki certificate</path> - </completionHelp> - </properties> - <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --certificate "$5"</command> - </leafNode> - </children> <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --certificate "all"</command> - </node> - <node name="crl"> + </leafNode> + <tagNode name="certificate"> <properties> - <help>Show certificate revocation lists</help> + <help>Show x509 certificate by name</help> + <completionHelp> + <path>pki certificate</path> + </completionHelp> + </properties> + <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --certificate "$4"</command> + </tagNode> + <leafNode name="crl"> + <properties> + <help>Show x509 certificate revocation lists</help> </properties> - <children> - <leafNode name="name"> - <properties> - <help>Show certificate revocation lists from specified CA</help> - <completionHelp> - <path>pki ca</path> - </completionHelp> - </properties> - <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --crl "$5"</command> - </leafNode> - </children> <command>sudo ${vyos_op_scripts_dir}/pki.py --action show --crl "all"</command> - </node> + </leafNode> </children> <command>sudo ${vyos_op_scripts_dir}/pki.py --action show</command> </node> diff --git a/python/vyos/airbag.py b/python/vyos/airbag.py index a20f44207..3c7a144b7 100644 --- a/python/vyos/airbag.py +++ b/python/vyos/airbag.py @@ -125,14 +125,14 @@ def _intercepting_exceptions(_singleton=[False]): # if the key before the value has not time, syslog takes that as the source of the message FAULT = """\ -Report Time: {date} -Image Version: VyOS {version} -Release Train: {release_train} +Report time: {date} +Image version: VyOS {version} +Release train: {release_train} Built by: {built_by} Built on: {built_on} Build UUID: {build_uuid} -Build Commit ID: {build_git} +Build commit ID: {build_git} Architecture: {system_arch} Boot via: {boot_via} diff --git a/python/vyos/template.py b/python/vyos/template.py index ee6e52e1d..d13915766 100644 --- a/python/vyos/template.py +++ b/python/vyos/template.py @@ -393,8 +393,15 @@ def get_ip(interface): from vyos.ifconfig import Interface return Interface(interface).get_addr() +def get_first_ike_dh_group(ike_group): + if ike_group and 'proposal' in ike_group: + for priority, proposal in ike_group['proposal'].items(): + if 'dh_group' in proposal: + return 'dh-group' + proposal['dh_group'] + return 'dh-group2' # Fallback on dh-group2 + @register_filter('get_esp_ike_cipher') -def get_esp_ike_cipher(group_config): +def get_esp_ike_cipher(group_config, ike_group=None): pfs_lut = { 'dh-group1' : 'modp768', 'dh-group2' : 'modp1024', @@ -433,7 +440,7 @@ def get_esp_ike_cipher(group_config): elif 'pfs' in group_config and group_config['pfs'] != 'disable': group = group_config['pfs'] if group_config['pfs'] == 'enable': - group = 'dh-group2' + group = get_first_ike_dh_group(ike_group) tmp += '-' + pfs_lut[group] ciphers.append(tmp) diff --git a/smoketest/scripts/cli/test_service_webproxy.py b/smoketest/scripts/cli/test_service_webproxy.py index d47bd452d..6780a93f9 100755 --- a/smoketest/scripts/cli/test_service_webproxy.py +++ b/smoketest/scripts/cli/test_service_webproxy.py @@ -52,8 +52,6 @@ class TestServiceWebProxy(VyOSUnitTestSHIM.TestCase): self.assertIn(f'access_log /var/log/squid/access.log squid', config) # ACL verification - self.assertIn(f'acl localhost src 127.0.0.1/32', config) - self.assertIn(f'acl to_localhost dst 127.0.0.0/8', config) self.assertIn(f'acl net src all', config) self.assertIn(f'acl SSL_ports port 443', config) @@ -234,8 +232,8 @@ class TestServiceWebProxy(VyOSUnitTestSHIM.TestCase): config = read_file(PROXY_CONF) self.assertIn(f'http_port {listen_ip}:3128 intercept', config) - self.assertIn(f'redirect_program /usr/bin/squidGuard -c /etc/squidguard/squidGuard.conf', config) - self.assertIn(f'redirect_children 8', config) + self.assertIn(f'url_rewrite_program /usr/bin/squidGuard -c /etc/squidguard/squidGuard.conf', config) + self.assertIn(f'url_rewrite_children 8', config) # Check SquidGuard config sg_config = read_file('/etc/squidguard/squidGuard.conf') diff --git a/src/conf_mode/service_webproxy.py b/src/conf_mode/service_webproxy.py index cbbd2e0bc..a16cc4aeb 100755 --- a/src/conf_mode/service_webproxy.py +++ b/src/conf_mode/service_webproxy.py @@ -23,6 +23,7 @@ from vyos.config import Config from vyos.configdict import dict_merge from vyos.template import render from vyos.util import call +from vyos.util import chmod_755 from vyos.util import dict_search from vyos.util import write_file from vyos.validate import is_addr_assigned @@ -192,6 +193,8 @@ def apply(proxy): return None + if os.path.exists(squidguard_db_dir): + chmod_755(squidguard_db_dir) call('systemctl restart squid.service') return None diff --git a/src/conf_mode/vpn_ipsec.py b/src/conf_mode/vpn_ipsec.py index ff6090e22..99b82ca2d 100755 --- a/src/conf_mode/vpn_ipsec.py +++ b/src/conf_mode/vpn_ipsec.py @@ -362,6 +362,9 @@ def verify(ipsec): if 'authentication' not in peer_conf or 'mode' not in peer_conf['authentication']: raise ConfigError(f"Missing authentication on site-to-site peer {peer}") + if {'id', 'use_x509_id'} <= set(peer_conf['authentication']): + raise ConfigError(f"Manually set peer id and use-x509-id are mutually exclusive!") + if peer_conf['authentication']['mode'] == 'x509': if 'x509' not in peer_conf['authentication']: raise ConfigError(f"Missing x509 settings on site-to-site peer {peer}") diff --git a/src/op_mode/pki.py b/src/op_mode/pki.py index d28cee5d0..e1428c581 100755 --- a/src/op_mode/pki.py +++ b/src/op_mode/pki.py @@ -23,6 +23,7 @@ import tabulate from cryptography import x509 from cryptography.x509.oid import ExtendedKeyUsageOID +from vyos.config import Config from vyos.configquery import ConfigTreeQuery from vyos.configdict import dict_merge from vyos.pki import encode_certificate, encode_public_key, encode_private_key, encode_dh_parameters @@ -36,7 +37,6 @@ from vyos.util import ask_input, ask_yes_no from vyos.util import cmd CERT_REQ_END = '-----END CERTIFICATE REQUEST-----' - auth_dir = '/config/auth' # Helper Functions @@ -216,17 +216,39 @@ def install_wireguard_key(interface, private_key, public_key): print(f'"{interface}" is not a WireGuard interface name!') exit(1) - print("Configure mode commands to install key:", end="\n\n") - print(f"set interfaces wireguard {interface} private-key '{private_key}'", end="\n\n") - print(f"Public key to use on peer system: '{public_key}'") + # Check if we are running in a config session - if yes, we can directly write to the CLI + cli_string = f"interfaces wireguard {interface} private-key '{private_key}'" + if Config().in_session(): + cmd(f"/opt/vyatta/sbin/my_set {cli_string}") + + print('"generate" CLI command executed from config session.\nGenerated private-key was imported to CLI!',end='\n\n') + print(f'Use the following command to verify: show interfaces wireguard {interface}') + else: + print('"generate" CLI command executed from operational level.\n' + 'Generated private-key is not stored to CLI, use configure mode commands to install key:', end='\n\n') + print(f"set {cli_string}", end="\n\n") + + print(f"Corresponding public-key to use on peer system is: '{public_key}'") + def install_wireguard_psk(interface, peer, psk): from vyos.ifconfig import Section if Section.section(interface) != 'wireguard': print(f'"{interface}" is not a WireGuard interface name!') exit(1) - # Show conf commands for installing wireguard psk - print(f"set interfaces wireguard {interface} peer {peer} preshared-key '{psk}'") + + # Check if we are running in a config session - if yes, we can directly write to the CLI + cli_string = f"interfaces wireguard {interface} peer {peer} preshared-key '{psk}'" + if Config().in_session(): + cmd(f"/opt/vyatta/sbin/my_set {cli_string}") + + print('"generate" CLI command executed from config session.\nGenerated preshared-key was imported to CLI!',end='\n\n') + print(f'Use the following command to verify: show interfaces wireguard {interface}') + else: + print('"generate" CLI command executed from operational level.\n' + 'Generated preshared-key is not stored to CLI, use configure mode commands to install key:', end='\n\n') + print(f"set {cli_string}", end="\n\n") + def ask_passphrase(): passphrase = None @@ -825,6 +847,10 @@ if __name__ == '__main__': generate_openvpn_key(args.openvpn, install=args.install, file=args.file) elif args.wireguard: + # WireGuard supports writing key directly into the CLI, but this + # requires the vyos_libexec_dir environment variable to be set + os.environ["vyos_libexec_dir"] = "/usr/libexec/vyos" + if args.key: generate_wireguard_key(args.interface, install=args.install) if args.psk: diff --git a/src/op_mode/restart_frr.py b/src/op_mode/restart_frr.py index 0b2322478..109c8dd7b 100755 --- a/src/op_mode/restart_frr.py +++ b/src/op_mode/restart_frr.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # -# Copyright (C) 2019 VyOS maintainers and contributors +# 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 @@ -13,16 +13,19 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -# -import sys +import os import argparse import logging -from logging.handlers import SysLogHandler -from pathlib import Path import psutil +from logging.handlers import SysLogHandler +from shutil import rmtree + from vyos.util import call +from vyos.util import ask_yes_no +from vyos.util import process_named_running +from vyos.util import makedir # some default values watchfrr = '/usr/lib/frr/watchfrr.sh' @@ -40,40 +43,45 @@ logger.setLevel(logging.INFO) def _check_safety(): try: # print warning - answer = input("WARNING: This is a potentially unsafe function! You may lose the connection to the router or active configuration after running this command. Use it at your own risk! Continue? [y/N]: ") - if not answer.lower() == "y": - logger.error("User aborted command") + if not ask_yes_no('WARNING: This is a potentially unsafe function!\n' \ + 'You may lose the connection to the router or active configuration after\n' \ + 'running this command. Use it at your own risk!\n\n' + 'Continue?'): return False # check if another restart process already running if len([process for process in psutil.process_iter(attrs=['pid', 'name', 'cmdline']) if 'python' in process.info['name'] and 'restart_frr.py' in process.info['cmdline'][1]]) > 1: - logger.error("Another restart_frr.py already running") - answer = input("Another restart_frr.py process is already running. It is unsafe to continue. Do you want to process anyway? [y/N]: ") - if not answer.lower() == "y": + message = 'Another restart_frr.py process is already running!' + logger.error(message) + if not ask_yes_no(f'\n{message} It is unsafe to continue.\n\n' \ + 'Do you want to process anyway?'): return False # check if watchfrr.sh is running - for process in psutil.process_iter(attrs=['pid', 'name', 'cmdline']): - if 'bash' in process.info['name'] and watchfrr in process.info['cmdline']: - logger.error("Another {} already running".format(watchfrr)) - answer = input("Another {} process is already running. It is unsafe to continue. Do you want to process anyway? [y/N]: ".format(watchfrr)) - if not answer.lower() == "y": - return False + tmp = os.path.basename(watchfrr) + if process_named_running(tmp): + message = f'Another {tmp} process is already running.' + logger.error(message) + if not ask_yes_no(f'{message} It is unsafe to continue.\n\n' \ + 'Do you want to process anyway?'): + return False # check if vtysh is running - for process in psutil.process_iter(attrs=['pid', 'name', 'cmdline']): - if 'vtysh' in process.info['name']: - logger.error("The vtysh is running by another task") - answer = input("The vtysh is running by another task. It is unsafe to continue. Do you want to process anyway? [y/N]: ") - if not answer.lower() == "y": - return False + if process_named_running('vtysh'): + message = 'vtysh process is executed by another task.' + logger.error(message) + if not ask_yes_no(f'{message} It is unsafe to continue.\n\n' \ + 'Do you want to process anyway?'): + return False # check if temporary directory exists - if Path(frrconfig_tmp).exists(): - logger.error("The temporary directory \"{}\" already exists".format(frrconfig_tmp)) - answer = input("The temporary directory \"{}\" already exists. It is unsafe to continue. Do you want to process anyway? [y/N]: ".format(frrconfig_tmp)) - if not answer.lower() == "y": + if os.path.exists(frrconfig_tmp): + message = f'Temporary directory "{frrconfig_tmp}" already exists!' + logger.error(message) + if not ask_yes_no(f'{message} It is unsafe to continue.\n\n' \ + 'Do you want to process anyway?'): return False + except: logger.error("Something goes wrong in _check_safety()") return False @@ -84,72 +92,47 @@ def _check_safety(): # write active config to file def _write_config(): # create temporary directory - Path(frrconfig_tmp).mkdir(parents=False, exist_ok=True) + makedir(frrconfig_tmp) # save frr.conf to it - command = "{} -n -w --config_dir {} 2> /dev/null".format(vtysh, frrconfig_tmp) + command = f'{vtysh} -n -w --config_dir {frrconfig_tmp} 2> /dev/null' return_code = call(command) - if not return_code == 0: - logger.error("Failed to save active config: \"{}\" returned exit code: {}".format(command, return_code)) + if return_code != 0: + logger.error(f'Failed to save active config: "{command}" returned exit code: {return_code}') return False - logger.info("Active config saved to {}".format(frrconfig_tmp)) + logger.info(f'Active config saved to {frrconfig_tmp}') return True # clear and remove temporary directory def _cleanup(): - tmpdir = Path(frrconfig_tmp) - try: - if tmpdir.exists(): - for file in tmpdir.iterdir(): - file.unlink() - tmpdir.rmdir() - except: - logger.error("Failed to remove temporary directory {}".format(frrconfig_tmp)) - print("Failed to remove temporary directory {}".format(frrconfig_tmp)) - -# check if daemon is running -def _daemon_check(daemon): - command = "{} print_status {}".format(watchfrr, daemon) - return_code = call(command) - if not return_code == 0: - logger.error("Daemon \"{}\" is not running".format(daemon)) - return False - - # return True if all checks were passed - return True + if os.path.isdir(frrconfig_tmp): + rmtree(frrconfig_tmp) # restart daemon def _daemon_restart(daemon): - command = "{} restart {}".format(watchfrr, daemon) + command = f'{watchfrr} restart {daemon}' return_code = call(command) if not return_code == 0: - logger.error("Failed to restart daemon \"{}\"".format(daemon)) + logger.error(f'Failed to restart daemon "{daemon}"!') return False # return True if restarted successfully - logger.info("Daemon \"{}\" restarted".format(daemon)) + logger.info(f'Daemon "{daemon}" restarted!') return True # reload old config def _reload_config(daemon): if daemon != '': - command = "{} -n -b --config_dir {} -d {} 2> /dev/null".format(vtysh, frrconfig_tmp, daemon) + command = f'{vtysh} -n -b --config_dir {frrconfig_tmp} -d {daemon} 2> /dev/null' else: - command = "{} -n -b --config_dir {} 2> /dev/null".format(vtysh, frrconfig_tmp) + command = f'{vtysh} -n -b --config_dir {frrconfig_tmp} 2> /dev/null' return_code = call(command) if not return_code == 0: - logger.error("Failed to reinstall configuration") + logger.error('Failed to re-install configuration!') return False # return True if restarted successfully - logger.info("Configuration reinstalled successfully") - return True - -# check all daemons if they are running -def _check_args_daemon(daemons): - for daemon in daemons: - if not _daemon_check(daemon): - return False + logger.info('Configuration re-installed successfully!') return True # define program arguments @@ -159,19 +142,18 @@ cmd_args_parser.add_argument('--daemon', choices=['bfdd', 'bgpd', 'ospfd', 'ospf # parse arguments cmd_args = cmd_args_parser.parse_args() - # main logic # restart daemon if cmd_args.action == 'restart': # check if it is safe to restart FRR if not _check_safety(): print("\nOne of the safety checks was failed or user aborted command. Exiting.") - sys.exit(1) + exit(1) if not _write_config(): print("Failed to save active config") _cleanup() - sys.exit(1) + exit(1) # a little trick to make further commands more clear if not cmd_args.daemon: @@ -179,19 +161,20 @@ if cmd_args.action == 'restart': # check all daemons if they are running if cmd_args.daemon != ['']: - if not _check_args_daemon(cmd_args.daemon): - print("Warning: some of listed daemons are not running") + for daemon in cmd_args.daemon: + if not process_named_running(daemon): + print('WARNING: some of listed daemons are not running!') # run command to restart daemon for daemon in cmd_args.daemon: if not _daemon_restart(daemon): - print("Failed to restart daemon: {}".format(daemon)) + print('Failed to restart daemon: {daemon}') _cleanup() - sys.exit(1) + exit(1) # reinstall old configuration _reload_config(daemon) # cleanup after all actions _cleanup() -sys.exit(0) +exit(0) diff --git a/src/op_mode/show_version.py b/src/op_mode/show_version.py index 5bbc2e1f1..7962e1e7b 100755 --- a/src/op_mode/show_version.py +++ b/src/op_mode/show_version.py @@ -32,12 +32,12 @@ parser.add_argument("-j", "--json", action="store_true", help="Produce JSON outp version_output_tmpl = """ Version: VyOS {{version}} -Release Train: {{release_train}} +Release train: {{release_train}} Built by: {{built_by}} Built on: {{built_on}} Build UUID: {{build_uuid}} -Build Commit ID: {{build_git}} +Build commit ID: {{build_git}} Architecture: {{system_arch}} Boot via: {{boot_via}} diff --git a/src/systemd/dhcp6c@.service b/src/systemd/dhcp6c@.service index 9a97ee261..fdd6d7d88 100644 --- a/src/systemd/dhcp6c@.service +++ b/src/systemd/dhcp6c@.service @@ -9,7 +9,7 @@ StartLimitIntervalSec=0 WorkingDirectory=/run/dhcp6c Type=forking PIDFile=/run/dhcp6c/dhcp6c.%i.pid -ExecStart=/usr/sbin/dhcp6c -D -k /run/dhcp6c/dhcp6c.%i.sock -c /run/dhcp6c/dhcp6c.%i.conf -p /run/dhcp6c/dhcp6c.%i.pid %i +ExecStart=/usr/sbin/dhcp6c -k /run/dhcp6c/dhcp6c.%i.sock -c /run/dhcp6c/dhcp6c.%i.conf -p /run/dhcp6c/dhcp6c.%i.pid %i Restart=on-failure RestartSec=20 |