summaryrefslogtreecommitdiff
path: root/src/op_mode
diff options
context:
space:
mode:
Diffstat (limited to 'src/op_mode')
-rwxr-xr-xsrc/op_mode/dhcp.py9
-rwxr-xr-xsrc/op_mode/dns.py170
-rwxr-xr-xsrc/op_mode/dns_dynamic.py113
-rwxr-xr-xsrc/op_mode/dns_forwarding_reset.py54
-rwxr-xr-xsrc/op_mode/dns_forwarding_restart.sh8
-rwxr-xr-xsrc/op_mode/dns_forwarding_statistics.py32
-rwxr-xr-xsrc/op_mode/image_installer.py13
-rwxr-xr-xsrc/op_mode/image_manager.py25
-rwxr-xr-xsrc/op_mode/interfaces_wireless.py1
-rwxr-xr-xsrc/op_mode/multicast.py72
-rwxr-xr-xsrc/op_mode/pki.py12
-rwxr-xr-xsrc/op_mode/powerctrl.py4
-rwxr-xr-xsrc/op_mode/show_openvpn.py6
-rw-r--r--src/op_mode/zone.py215
14 files changed, 482 insertions, 252 deletions
diff --git a/src/op_mode/dhcp.py b/src/op_mode/dhcp.py
index 02f4d5bbb..a64acec31 100755
--- a/src/op_mode/dhcp.py
+++ b/src/op_mode/dhcp.py
@@ -194,14 +194,11 @@ def _get_pool_size(pool, family='inet'):
size = 0
subnets = config.list_nodes(f'{base} subnet')
for subnet in subnets:
- if family == 'inet6':
- ranges = config.list_nodes(f'{base} subnet {subnet} address-range start')
- else:
- ranges = config.list_nodes(f'{base} subnet {subnet} range')
+ ranges = config.list_nodes(f'{base} subnet {subnet} range')
for range in ranges:
if family == 'inet6':
- start = config.list_nodes(f'{base} subnet {subnet} address-range start')[0]
- stop = config.value(f'{base} subnet {subnet} address-range start {start} stop')
+ start = config.value(f'{base} subnet {subnet} range {range} start')
+ stop = config.value(f'{base} subnet {subnet} range {range} stop')
else:
start = config.value(f'{base} subnet {subnet} range {range} start')
stop = config.value(f'{base} subnet {subnet} range {range} stop')
diff --git a/src/op_mode/dns.py b/src/op_mode/dns.py
index 2168aef89..16c462f23 100755
--- a/src/op_mode/dns.py
+++ b/src/op_mode/dns.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
#
-# Copyright (C) 2022 VyOS maintainers and contributors
+# Copyright (C) 2022-2024 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
@@ -15,17 +15,35 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+import os
import sys
+import time
+import typing
+import vyos.opmode
from tabulate import tabulate
-
from vyos.configquery import ConfigTreeQuery
-from vyos.utils.process import cmd
-
-import vyos.opmode
-
-
-def _data_to_dict(data, sep="\t") -> dict:
+from vyos.utils.process import cmd, rc_cmd
+from vyos.template import is_ipv4, is_ipv6
+
+_dynamic_cache_file = r'/run/ddclient/ddclient.cache'
+
+_dynamic_status_columns = {
+ 'host': 'Hostname',
+ 'ipv4': 'IPv4 address',
+ 'status-ipv4': 'IPv4 status',
+ 'ipv6': 'IPv6 address',
+ 'status-ipv6': 'IPv6 status',
+ 'mtime': 'Last update',
+}
+
+_forwarding_statistics_columns = {
+ 'cache-entries': 'Cache entries',
+ 'max-cache-entries': 'Max cache entries',
+ 'cache-size': 'Cache size',
+}
+
+def _forwarding_data_to_dict(data, sep="\t") -> dict:
"""
Return dictionary from plain text
separated by tab
@@ -51,37 +69,135 @@ def _data_to_dict(data, sep="\t") -> dict:
dictionary[key] = value
return dictionary
+def _get_dynamic_host_records_raw() -> dict:
+
+ data = []
+
+ if os.path.isfile(_dynamic_cache_file): # A ddclient status file might not always exist
+ with open(_dynamic_cache_file, 'r') as f:
+ for line in f:
+ if line.startswith('#'):
+ continue
+
+ props = {}
+ # ddclient cache rows have properties in 'key=value' format separated by comma
+ # we pick up the ones we are interested in
+ for kvraw in line.split(' ')[0].split(','):
+ k, v = kvraw.split('=')
+ if k in list(_dynamic_status_columns.keys()) + ['ip', 'status']: # ip and status are legacy keys
+ props[k] = v
+
+ # Extract IPv4 and IPv6 address and status from legacy keys
+ # Dual-stack isn't supported in legacy format, 'ip' and 'status' are for one of IPv4 or IPv6
+ if 'ip' in props:
+ if is_ipv4(props['ip']):
+ props['ipv4'] = props['ip']
+ props['status-ipv4'] = props['status']
+ elif is_ipv6(props['ip']):
+ props['ipv6'] = props['ip']
+ props['status-ipv6'] = props['status']
+ del props['ip']
+
+ # Convert mtime to human readable format
+ if 'mtime' in props:
+ props['mtime'] = time.strftime(
+ "%Y-%m-%d %H:%M:%S", time.localtime(int(props['mtime'], base=10)))
+
+ data.append(props)
-def _get_raw_forwarding_statistics() -> dict:
- command = cmd('rec_control --socket-dir=/run/powerdns get-all')
- data = _data_to_dict(command)
- data['cache-size'] = "{0:.2f}".format( int(
- cmd('rec_control --socket-dir=/run/powerdns get cache-bytes')) / 1024 )
return data
-
-def _get_formatted_forwarding_statistics(data):
- cache_entries = data.get('cache-entries')
- max_cache_entries = data.get('max-cache-entries')
- cache_size = data.get('cache-size')
- data_entries = [[cache_entries, max_cache_entries, f'{cache_size} kbytes']]
- headers = ["Cache entries", "Max cache entries" , "Cache size"]
- output = tabulate(data_entries, headers, numalign="left")
+def _get_dynamic_host_records_formatted(data):
+ data_entries = []
+ for entry in data:
+ data_entries.append([entry.get(key) for key in _dynamic_status_columns.keys()])
+ header = _dynamic_status_columns.values()
+ output = tabulate(data_entries, header, numalign='left')
return output
+def _get_forwarding_statistics_raw() -> dict:
+ command = cmd('rec_control get-all')
+ data = _forwarding_data_to_dict(command)
+ data['cache-size'] = "{0:.2f} kbytes".format( int(
+ cmd('rec_control get cache-bytes')) / 1024 )
+ return data
-def show_forwarding_statistics(raw: bool):
+def _get_forwarding_statistics_formatted(data):
+ data_entries = []
+ data_entries.append([data.get(key) for key in _forwarding_statistics_columns.keys()])
+ header = _forwarding_statistics_columns.values()
+ output = tabulate(data_entries, header, numalign='left')
+ return output
- config = ConfigTreeQuery()
- if not config.exists('service dns forwarding'):
- raise vyos.opmode.UnconfiguredSubsystem('DNS forwarding is not configured')
+def _verify(target):
+ """Decorator checks if config for DNS related service exists"""
+ from functools import wraps
+
+ if target not in ['dynamic', 'forwarding']:
+ raise ValueError('Invalid target')
+
+ def _verify_target(func):
+ @wraps(func)
+ def _wrapper(*args, **kwargs):
+ config = ConfigTreeQuery()
+ if not config.exists(f'service dns {target}'):
+ _prefix = f'Dynamic DNS' if target == 'dynamic' else 'DNS Forwarding'
+ raise vyos.opmode.UnconfiguredSubsystem(f'{_prefix} is not configured')
+ return func(*args, **kwargs)
+ return _wrapper
+ return _verify_target
+
+@_verify('dynamic')
+def show_dynamic_status(raw: bool):
+ host_data = _get_dynamic_host_records_raw()
+ if raw:
+ return host_data
+ else:
+ return _get_dynamic_host_records_formatted(host_data)
- dns_data = _get_raw_forwarding_statistics()
+@_verify('dynamic')
+def reset_dynamic():
+ """
+ Reset Dynamic DNS cache
+ """
+ if os.path.exists(_dynamic_cache_file):
+ os.remove(_dynamic_cache_file)
+ rc, output = rc_cmd('systemctl restart ddclient.service')
+ if rc != 0:
+ print(output)
+ return None
+ print(f'Dynamic DNS state reset!')
+
+@_verify('forwarding')
+def show_forwarding_statistics(raw: bool):
+ dns_data = _get_forwarding_statistics_raw()
if raw:
return dns_data
else:
- return _get_formatted_forwarding_statistics(dns_data)
+ return _get_forwarding_statistics_formatted(dns_data)
+
+@_verify('forwarding')
+def reset_forwarding(all: bool, domain: typing.Optional[str]):
+ """
+ Reset DNS Forwarding cache
+ :param all (bool): reset cache all domains
+ :param domain (str): reset cache for specified domain
+ """
+ if all:
+ rc, output = rc_cmd('rec_control wipe-cache ".$"')
+ if rc != 0:
+ print(output)
+ return None
+ print('DNS Forwarding cache reset for all domains!')
+ return output
+ elif domain:
+ rc, output = rc_cmd(f'rec_control wipe-cache "{domain}$"')
+ if rc != 0:
+ print(output)
+ return None
+ print(f'DNS Forwarding cache reset for domain "{domain}"!')
+ return output
if __name__ == '__main__':
try:
diff --git a/src/op_mode/dns_dynamic.py b/src/op_mode/dns_dynamic.py
deleted file mode 100755
index 12aa5494a..000000000
--- a/src/op_mode/dns_dynamic.py
+++ /dev/null
@@ -1,113 +0,0 @@
-#!/usr/bin/env python3
-#
-# Copyright (C) 2018-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 argparse
-import sys
-import time
-from tabulate import tabulate
-
-from vyos.config import Config
-from vyos.template import is_ipv4, is_ipv6
-from vyos.utils.process import call
-
-cache_file = r'/run/ddclient/ddclient.cache'
-
-columns = {
- 'host': 'Hostname',
- 'ipv4': 'IPv4 address',
- 'status-ipv4': 'IPv4 status',
- 'ipv6': 'IPv6 address',
- 'status-ipv6': 'IPv6 status',
- 'mtime': 'Last update',
-}
-
-
-def _get_formatted_host_records(host_data):
- data_entries = []
- for entry in host_data:
- data_entries.append([entry.get(key) for key in columns.keys()])
-
- header = columns.values()
- output = tabulate(data_entries, header, numalign='left')
- return output
-
-
-def show_status():
- # A ddclient status file might not always exist
- if not os.path.exists(cache_file):
- sys.exit(0)
-
- data = []
-
- with open(cache_file, 'r') as f:
- for line in f:
- if line.startswith('#'):
- continue
-
- props = {}
- # ddclient cache rows have properties in 'key=value' format separated by comma
- # we pick up the ones we are interested in
- for kvraw in line.split(' ')[0].split(','):
- k, v = kvraw.split('=')
- if k in list(columns.keys()) + ['ip', 'status']: # ip and status are legacy keys
- props[k] = v
-
- # Extract IPv4 and IPv6 address and status from legacy keys
- # Dual-stack isn't supported in legacy format, 'ip' and 'status' are for one of IPv4 or IPv6
- if 'ip' in props:
- if is_ipv4(props['ip']):
- props['ipv4'] = props['ip']
- props['status-ipv4'] = props['status']
- elif is_ipv6(props['ip']):
- props['ipv6'] = props['ip']
- props['status-ipv6'] = props['status']
- del props['ip']
-
- # Convert mtime to human readable format
- if 'mtime' in props:
- props['mtime'] = time.strftime(
- "%Y-%m-%d %H:%M:%S", time.localtime(int(props['mtime'], base=10)))
-
- data.append(props)
-
- print(_get_formatted_host_records(data))
-
-
-def update_ddns():
- call('systemctl stop ddclient.service')
- if os.path.exists(cache_file):
- os.remove(cache_file)
- call('systemctl start ddclient.service')
-
-
-if __name__ == '__main__':
- parser = argparse.ArgumentParser()
- group = parser.add_mutually_exclusive_group()
- group.add_argument("--status", help="Show DDNS status", action="store_true")
- group.add_argument("--update", help="Update DDNS on a given interface", action="store_true")
- args = parser.parse_args()
-
- # Do nothing if service is not configured
- c = Config()
- if not c.exists_effective('service dns dynamic'):
- print("Dynamic DNS not configured")
- sys.exit(1)
-
- if args.status:
- show_status()
- elif args.update:
- update_ddns()
diff --git a/src/op_mode/dns_forwarding_reset.py b/src/op_mode/dns_forwarding_reset.py
deleted file mode 100755
index 55e20918f..000000000
--- a/src/op_mode/dns_forwarding_reset.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python3
-#
-# Copyright (C) 2018 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/>.
-#
-# File: vyos-show-version
-# Purpose:
-# Displays image version and system information.
-# Used by the "run show version" command.
-
-
-import os
-import argparse
-
-from sys import exit
-from vyos.config import Config
-from vyos.utils.process import call
-
-PDNS_CMD='/usr/bin/rec_control --socket-dir=/run/powerdns'
-
-parser = argparse.ArgumentParser()
-parser.add_argument("-a", "--all", action="store_true", help="Reset all cache")
-parser.add_argument("domain", type=str, nargs="?", help="Domain to reset cache entries for")
-
-if __name__ == '__main__':
- args = parser.parse_args()
-
- # Do nothing if service is not configured
- c = Config()
- if not c.exists_effective(['service', 'dns', 'forwarding']):
- print("DNS forwarding is not configured")
- exit(0)
-
- if args.all:
- call(f"{PDNS_CMD} wipe-cache \'.$\'")
- exit(0)
-
- elif args.domain:
- call(f"{PDNS_CMD} wipe-cache \'{0}$\'".format(args.domain))
-
- else:
- parser.print_help()
- exit(1)
diff --git a/src/op_mode/dns_forwarding_restart.sh b/src/op_mode/dns_forwarding_restart.sh
deleted file mode 100755
index 64cc92115..000000000
--- a/src/op_mode/dns_forwarding_restart.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/sh
-
-if cli-shell-api existsEffective service dns forwarding; then
- echo "Restarting the DNS forwarding service"
- systemctl restart pdns-recursor.service
-else
- echo "DNS forwarding is not configured"
-fi
diff --git a/src/op_mode/dns_forwarding_statistics.py b/src/op_mode/dns_forwarding_statistics.py
deleted file mode 100755
index 32b5c76a7..000000000
--- a/src/op_mode/dns_forwarding_statistics.py
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/env python3
-
-import jinja2
-from sys import exit
-
-from vyos.config import Config
-from vyos.utils.process import cmd
-
-PDNS_CMD='/usr/bin/rec_control --socket-dir=/run/powerdns'
-
-OUT_TMPL_SRC = """
-DNS forwarding statistics:
-
-Cache entries: {{ cache_entries }}
-Cache size: {{ cache_size }} kbytes
-
-"""
-
-if __name__ == '__main__':
- # Do nothing if service is not configured
- c = Config()
- if not c.exists_effective('service dns forwarding'):
- print("DNS forwarding is not configured")
- exit(0)
-
- data = {}
-
- data['cache_entries'] = cmd(f'{PDNS_CMD} get cache-entries')
- data['cache_size'] = "{0:.2f}".format( int(cmd(f'{PDNS_CMD} get cache-bytes')) / 1024 )
-
- tmpl = jinja2.Template(OUT_TMPL_SRC)
- print(tmpl.render(data))
diff --git a/src/op_mode/image_installer.py b/src/op_mode/image_installer.py
index 791d76718..501e9b804 100755
--- a/src/op_mode/image_installer.py
+++ b/src/op_mode/image_installer.py
@@ -69,8 +69,8 @@ MSG_WARN_ISO_SIGN_INVALID: str = 'Signature is not valid. Do you want to continu
MSG_WARN_ISO_SIGN_UNAVAL: str = 'Signature is not available. Do you want to continue with installation?'
MSG_WARN_ROOT_SIZE_TOOBIG: str = 'The size is too big. Try again.'
MSG_WARN_ROOT_SIZE_TOOSMALL: str = 'The size is too small. Try again'
-MSG_WARN_IMAGE_NAME_WRONG: str = 'The suggested name is unsupported!\n'
-'It must be between 1 and 32 characters long and contains only the next characters: .+-_ a-z A-Z 0-9'
+MSG_WARN_IMAGE_NAME_WRONG: str = 'The suggested name is unsupported!\n'\
+'It must be between 1 and 64 characters long and contains only the next characters: .+-_ a-z A-Z 0-9'
CONST_MIN_DISK_SIZE: int = 2147483648 # 2 GB
CONST_MIN_ROOT_SIZE: int = 1610612736 # 1.5 GB
# a reserved space: 2MB for header, 1 MB for BIOS partition, 256 MB for EFI
@@ -93,6 +93,7 @@ DEFAULT_BOOT_VARS: dict[str, str] = {
'timeout': '5',
'console_type': 'tty',
'console_num': '0',
+ 'console_speed': '115200',
'bootmode': 'normal'
}
@@ -811,7 +812,11 @@ def add_image(image_path: str, vrf: str = None, username: str = '',
f'Adding image would downgrade image tools to v.{cfg_ver}; disallowed')
if not no_prompt:
- image_name: str = ask_input(MSG_INPUT_IMAGE_NAME, version_name)
+ while True:
+ image_name: str = ask_input(MSG_INPUT_IMAGE_NAME, version_name)
+ if image.validate_name(image_name):
+ break
+ print(MSG_WARN_IMAGE_NAME_WRONG)
set_as_default: bool = ask_yes_no(MSG_INPUT_IMAGE_DEFAULT, default=True)
else:
image_name: str = version_name
@@ -866,7 +871,7 @@ def add_image(image_path: str, vrf: str = None, username: str = '',
except Exception as err:
# unmount an ISO and cleanup
cleanup([str(iso_path)])
- exit(f'Whooops: {err}')
+ exit(f'Error: {err}')
def parse_arguments() -> Namespace:
diff --git a/src/op_mode/image_manager.py b/src/op_mode/image_manager.py
index e75485f9f..e64a85b95 100755
--- a/src/op_mode/image_manager.py
+++ b/src/op_mode/image_manager.py
@@ -33,6 +33,27 @@ DELETE_IMAGE_PROMPT_MSG: str = 'Select an image to delete:'
MSG_DELETE_IMAGE_RUNNING: str = 'Currently running image cannot be deleted; reboot into another image first'
MSG_DELETE_IMAGE_DEFAULT: str = 'Default image cannot be deleted; set another image as default first'
+def annotated_list(images_list: list[str]) -> list[str]:
+ """Annotate list of images with additional info
+
+ Args:
+ images_list (list[str]): a list of image names
+
+ Returns:
+ list[str]: a list of image names with additional info
+ """
+ index_running: int = None
+ index_default: int = None
+ try:
+ index_running = images_list.index(image.get_running_image())
+ index_default = images_list.index(image.get_default_image())
+ except ValueError:
+ pass
+ if index_running is not None:
+ images_list[index_running] += ' (running)'
+ if index_default is not None:
+ images_list[index_default] += ' (default boot)'
+ return images_list
@compat.grub_cfg_update
def delete_image(image_name: Optional[str] = None,
@@ -42,7 +63,7 @@ def delete_image(image_name: Optional[str] = None,
Args:
image_name (str): a name of image to delete
"""
- available_images: list[str] = grub.version_list()
+ available_images: list[str] = annotated_list(grub.version_list())
if image_name is None:
if no_prompt:
exit('An image name is required for delete action')
@@ -83,7 +104,7 @@ def set_image(image_name: Optional[str] = None,
Args:
image_name (str): an image name
"""
- available_images: list[str] = grub.version_list()
+ available_images: list[str] = annotated_list(grub.version_list())
if image_name is None:
if not prompt:
exit('An image name is required for set action')
diff --git a/src/op_mode/interfaces_wireless.py b/src/op_mode/interfaces_wireless.py
index dfe50e2cb..259fd3900 100755
--- a/src/op_mode/interfaces_wireless.py
+++ b/src/op_mode/interfaces_wireless.py
@@ -32,6 +32,7 @@ def _verify(func):
def _wrapper(*args, **kwargs):
config = ConfigTreeQuery()
if not config.exists(['interfaces', 'wireless']):
+ unconf_message = 'No Wireless interfaces configured'
raise vyos.opmode.UnconfiguredSubsystem(unconf_message)
return func(*args, **kwargs)
return _wrapper
diff --git a/src/op_mode/multicast.py b/src/op_mode/multicast.py
new file mode 100755
index 000000000..0666f8af3
--- /dev/null
+++ b/src/op_mode/multicast.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2024 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 json
+import sys
+import typing
+
+from tabulate import tabulate
+from vyos.utils.process import cmd
+
+import vyos.opmode
+
+ArgFamily = typing.Literal['inet', 'inet6']
+
+def _get_raw_data(family, interface=None):
+ tmp = 'ip -4'
+ if family == 'inet6':
+ tmp = 'ip -6'
+ tmp = f'{tmp} -j maddr show'
+ if interface:
+ tmp = f'{tmp} dev {interface}'
+ output = cmd(tmp)
+ data = json.loads(output)
+ if not data:
+ return []
+ return data
+
+def _get_formatted_output(raw_data):
+ data_entries = []
+
+ # sort result by interface name
+ for interface in sorted(raw_data, key=lambda x: x['ifname']):
+ for address in interface['maddr']:
+ tmp = []
+ tmp.append(interface['ifname'])
+ tmp.append(address['family'])
+ tmp.append(address['address'])
+
+ data_entries.append(tmp)
+
+ headers = ["Interface", "Family", "Address"]
+ output = tabulate(data_entries, headers, numalign="left")
+ return output
+
+def show_group(raw: bool, family: ArgFamily, interface: typing.Optional[str]):
+ multicast_data = _get_raw_data(family=family, interface=interface)
+ if raw:
+ return multicast_data
+ else:
+ return _get_formatted_output(multicast_data)
+
+if __name__ == "__main__":
+ try:
+ res = vyos.opmode.run(sys.modules[__name__])
+ if res:
+ print(res)
+ except (ValueError, vyos.opmode.Error) as e:
+ print(e)
+ sys.exit(1)
diff --git a/src/op_mode/pki.py b/src/op_mode/pki.py
index 6c854afb5..ad2c1ada0 100755
--- a/src/op_mode/pki.py
+++ b/src/op_mode/pki.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
#
-# Copyright (C) 2021-2023 VyOS maintainers and contributors
+# Copyright (C) 2021-2024 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
@@ -25,6 +25,7 @@ from cryptography import x509
from cryptography.x509.oid import ExtendedKeyUsageOID
from vyos.config import Config
+from vyos.config import config_dict_mangle_acme
from vyos.pki import encode_certificate, encode_public_key, encode_private_key, encode_dh_parameters
from vyos.pki import get_certificate_fingerprint
from vyos.pki import create_certificate, create_certificate_request, create_certificate_revocation_list
@@ -79,9 +80,14 @@ def get_config_certificate(name=None):
if not conf.exists(base + ['private', 'key']) or not conf.exists(base + ['certificate']):
return False
- return conf.get_config_dict(base, key_mangling=('-', '_'),
+ pki = conf.get_config_dict(base, key_mangling=('-', '_'),
get_first_key=True,
no_tag_node_value_mangle=True)
+ if pki:
+ for certificate in pki:
+ pki[certificate] = config_dict_mangle_acme(certificate, pki[certificate])
+
+ return pki
def get_certificate_ca(cert, ca_certs):
# Find CA certificate for given certificate
@@ -1073,7 +1079,9 @@ if __name__ == '__main__':
show_crl(None if args.crl == 'all' else args.crl, args.pem)
else:
show_certificate_authority()
+ print('\n')
show_certificate()
+ print('\n')
show_crl()
except KeyboardInterrupt:
print("Aborted")
diff --git a/src/op_mode/powerctrl.py b/src/op_mode/powerctrl.py
index 3ac5991b4..c07d0c4bd 100755
--- a/src/op_mode/powerctrl.py
+++ b/src/op_mode/powerctrl.py
@@ -191,7 +191,7 @@ def main():
nargs="*",
metavar="HH:MM")
- action.add_argument("--reboot_in", "-i",
+ action.add_argument("--reboot-in", "-i",
help="Reboot the system",
nargs="*",
metavar="Minutes")
@@ -214,7 +214,7 @@ def main():
if args.reboot is not None:
for r in args.reboot:
if ':' not in r and '/' not in r and '.' not in r:
- print("Incorrect format! Use HH:MM")
+ print("Incorrect format! Use HH:MM")
exit(1)
execute_shutdown(args.reboot, reboot=True, ask=args.yes)
if args.reboot_in is not None:
diff --git a/src/op_mode/show_openvpn.py b/src/op_mode/show_openvpn.py
index e29e594a5..6abafc8b6 100755
--- a/src/op_mode/show_openvpn.py
+++ b/src/op_mode/show_openvpn.py
@@ -63,9 +63,11 @@ def get_vpn_tunnel_address(peer, interface):
# filter out subnet entries
lst = [l for l in lst[1:] if '/' not in l.split(',')[0]]
- tunnel_ip = lst[0].split(',')[0]
+ if lst:
+ tunnel_ip = lst[0].split(',')[0]
+ return tunnel_ip
- return tunnel_ip
+ return 'n/a'
def get_status(mode, interface):
status_file = '/var/run/openvpn/{}.status'.format(interface)
diff --git a/src/op_mode/zone.py b/src/op_mode/zone.py
new file mode 100644
index 000000000..d24b1065b
--- /dev/null
+++ b/src/op_mode/zone.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2024 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 typing
+import sys
+import vyos.opmode
+
+import tabulate
+from vyos.configquery import ConfigTreeQuery
+from vyos.utils.dict import dict_search_args
+from vyos.utils.dict import dict_search
+
+
+def get_config_zone(conf, name=None):
+ config_path = ['firewall', 'zone']
+ if name:
+ config_path += [name]
+
+ zone_policy = conf.get_config_dict(config_path, key_mangling=('-', '_'),
+ get_first_key=True,
+ no_tag_node_value_mangle=True)
+ return zone_policy
+
+
+def _convert_one_zone_data(zone: str, zone_config: dict) -> dict:
+ """
+ Convert config dictionary of one zone to API dictionary
+ :param zone: Zone name
+ :type zone: str
+ :param zone_config: config dictionary
+ :type zone_config: dict
+ :return: AP dictionary
+ :rtype: dict
+ """
+ list_of_rules = []
+ intrazone_dict = {}
+ if dict_search('from', zone_config):
+ for from_zone, from_zone_config in zone_config['from'].items():
+ from_zone_dict = {'name': from_zone}
+ if dict_search('firewall.name', from_zone_config):
+ from_zone_dict['firewall'] = dict_search('firewall.name',
+ from_zone_config)
+ if dict_search('firewall.ipv6_name', from_zone_config):
+ from_zone_dict['firewall_v6'] = dict_search(
+ 'firewall.ipv6_name', from_zone_config)
+ list_of_rules.append(from_zone_dict)
+
+ zone_dict = {
+ 'name': zone,
+ 'interface': dict_search('interface', zone_config),
+ 'type': 'LOCAL' if dict_search('local_zone',
+ zone_config) is not None else None,
+ }
+ if list_of_rules:
+ zone_dict['from'] = list_of_rules
+ if dict_search('intra_zone_filtering.firewall.name', zone_config):
+ intrazone_dict['firewall'] = dict_search(
+ 'intra_zone_filtering.firewall.name', zone_config)
+ if dict_search('intra_zone_filtering.firewall.ipv6_name', zone_config):
+ intrazone_dict['firewall_v6'] = dict_search(
+ 'intra_zone_filtering.firewall.ipv6_name', zone_config)
+ if intrazone_dict:
+ zone_dict['intrazone'] = intrazone_dict
+ return zone_dict
+
+
+def _convert_zones_data(zone_policies: dict) -> list:
+ """
+ Convert all config dictionary to API list of zone dictionaries
+ :param zone_policies: config dictionary
+ :type zone_policies: dict
+ :return: API list
+ :rtype: list
+ """
+ zone_list = []
+ for zone, zone_config in zone_policies.items():
+ zone_list.append(_convert_one_zone_data(zone, zone_config))
+ return zone_list
+
+
+def _convert_config(zones_config: dict, zone: str = None) -> list:
+ """
+ convert config to API list
+ :param zones_config: zones config
+ :type zones_config:
+ :param zone: zone name
+ :type zone: str
+ :return: API list
+ :rtype: list
+ """
+ if zone:
+ if zones_config:
+ output = [_convert_one_zone_data(zone, zones_config)]
+ else:
+ raise vyos.opmode.DataUnavailable(f'Zone {zone} not found')
+ else:
+ if zones_config:
+ output = _convert_zones_data(zones_config)
+ else:
+ raise vyos.opmode.UnconfiguredSubsystem(
+ 'Zone entries are not configured')
+ return output
+
+
+def output_zone_list(zone_conf: dict) -> list:
+ """
+ Format one zone row
+ :param zone_conf: zone config
+ :type zone_conf: dict
+ :return: formatted list of zones
+ :rtype: list
+ """
+ zone_info = [zone_conf['name']]
+ if zone_conf['type'] == 'LOCAL':
+ zone_info.append('LOCAL')
+ else:
+ zone_info.append("\n".join(zone_conf['interface']))
+
+ from_zone = []
+ firewall = []
+ firewall_v6 = []
+ if 'intrazone' in zone_conf:
+ from_zone.append(zone_conf['name'])
+
+ v4_name = dict_search_args(zone_conf['intrazone'], 'firewall')
+ v6_name = dict_search_args(zone_conf['intrazone'], 'firewall_v6')
+ if v4_name:
+ firewall.append(v4_name)
+ else:
+ firewall.append('')
+ if v6_name:
+ firewall_v6.append(v6_name)
+ else:
+ firewall_v6.append('')
+
+ if 'from' in zone_conf:
+ for from_conf in zone_conf['from']:
+ from_zone.append(from_conf['name'])
+
+ v4_name = dict_search_args(from_conf, 'firewall')
+ v6_name = dict_search_args(from_conf, 'firewall_v6')
+ if v4_name:
+ firewall.append(v4_name)
+ else:
+ firewall.append('')
+ if v6_name:
+ firewall_v6.append(v6_name)
+ else:
+ firewall_v6.append('')
+
+ zone_info.append("\n".join(from_zone))
+ zone_info.append("\n".join(firewall))
+ zone_info.append("\n".join(firewall_v6))
+ return zone_info
+
+
+def get_formatted_output(zone_policy: list) -> str:
+ """
+ Formatted output of all zones
+ :param zone_policy: list of zones
+ :type zone_policy: list
+ :return: formatted table with zones
+ :rtype: str
+ """
+ headers = ["Zone",
+ "Interfaces",
+ "From Zone",
+ "Firewall IPv4",
+ "Firewall IPv6"
+ ]
+ formatted_list = []
+ for zone_conf in zone_policy:
+ formatted_list.append(output_zone_list(zone_conf))
+ tabulate.PRESERVE_WHITESPACE = True
+ output = tabulate.tabulate(formatted_list, headers, numalign="left")
+ return output
+
+
+def show(raw: bool, zone: typing.Optional[str]):
+ """
+ Show zone-policy command
+ :param raw: if API
+ :type raw: bool
+ :param zone: zone name
+ :type zone: str
+ """
+ conf: ConfigTreeQuery = ConfigTreeQuery()
+ zones_config: dict = get_config_zone(conf, zone)
+ zone_policy_api: list = _convert_config(zones_config, zone)
+ if raw:
+ return zone_policy_api
+ else:
+ return get_formatted_output(zone_policy_api)
+
+
+if __name__ == '__main__':
+ try:
+ res = vyos.opmode.run(sys.modules[__name__])
+ if res:
+ print(res)
+ except (ValueError, vyos.opmode.Error) as e:
+ print(e)
+ sys.exit(1) \ No newline at end of file