diff options
Diffstat (limited to 'src')
-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 |
6 files changed, 98 insertions, 83 deletions
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 |