diff options
Diffstat (limited to 'src')
-rwxr-xr-x | src/completion/list_container_sysctl_parameters.sh | 20 | ||||
-rwxr-xr-x | src/conf_mode/container.py | 57 | ||||
-rwxr-xr-x | src/conf_mode/firewall.py | 44 | ||||
-rwxr-xr-x | src/conf_mode/load-balancing_reverse-proxy.py | 4 | ||||
-rwxr-xr-x | src/conf_mode/nat_cgnat.py | 71 | ||||
-rwxr-xr-x | src/conf_mode/pki.py | 4 | ||||
-rwxr-xr-x | src/conf_mode/system_conntrack.py | 3 | ||||
-rwxr-xr-x | src/migration-scripts/firewall/15-to-16 | 55 | ||||
-rwxr-xr-x | src/op_mode/cpu.py | 12 | ||||
-rwxr-xr-x | src/op_mode/ikev2_profile_generator.py | 36 | ||||
-rwxr-xr-x | src/op_mode/uptime.py | 4 |
11 files changed, 219 insertions, 91 deletions
diff --git a/src/completion/list_container_sysctl_parameters.sh b/src/completion/list_container_sysctl_parameters.sh new file mode 100755 index 000000000..cf8d006e5 --- /dev/null +++ b/src/completion/list_container_sysctl_parameters.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# +# 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/>. + +declare -a vals +eval "vals=($(/sbin/sysctl -N -a|grep -E '^(fs.mqueue|net)\.|^(kernel.msgmax|kernel.msgmnb|kernel.msgmni|kernel.sem|kernel.shmall|kernel.shmmax|kernel.shmmni|kernel.shm_rmid_forced)$'))" +echo ${vals[@]} +exit 0 diff --git a/src/conf_mode/container.py b/src/conf_mode/container.py index 3efeb9b40..ded370a7a 100755 --- a/src/conf_mode/container.py +++ b/src/conf_mode/container.py @@ -29,7 +29,7 @@ from vyos.configdict import node_changed from vyos.configdict import is_node_changed from vyos.configverify import verify_vrf from vyos.ifconfig import Interface -from vyos.cpu import get_core_count +from vyos.utils.cpu import get_core_count from vyos.utils.file import write_file from vyos.utils.process import call from vyos.utils.process import cmd @@ -43,6 +43,7 @@ from vyos.template import render from vyos.xml_ref import default_value from vyos import ConfigError from vyos import airbag + airbag.enable() config_containers = '/etc/containers/containers.conf' @@ -50,16 +51,19 @@ config_registry = '/etc/containers/registries.conf' config_storage = '/etc/containers/storage.conf' systemd_unit_path = '/run/systemd/system' + def _cmd(command): if os.path.exists('/tmp/vyos.container.debug'): print(command) return cmd(command) + def network_exists(name): # Check explicit name for network, returns True if network exists c = _cmd(f'podman network ls --quiet --filter name=^{name}$') return bool(c) + # Common functions def get_config(config=None): if config: @@ -86,21 +90,22 @@ def get_config(config=None): # registry is a tagNode with default values - merge the list from # default_values['registry'] into the tagNode variables if 'registry' not in container: - container.update({'registry' : {}}) + container.update({'registry': {}}) default_values = default_value(base + ['registry']) for registry in default_values: - tmp = {registry : {}} + tmp = {registry: {}} container['registry'] = dict_merge(tmp, container['registry']) # Delete container network, delete containers tmp = node_changed(conf, base + ['network']) - if tmp: container.update({'network_remove' : tmp}) + if tmp: container.update({'network_remove': tmp}) tmp = node_changed(conf, base + ['name']) - if tmp: container.update({'container_remove' : tmp}) + if tmp: container.update({'container_remove': tmp}) return container + def verify(container): # bail out early - looks like removal from running config if not container: @@ -125,8 +130,8 @@ def verify(container): # of image upgrade and deletion. image = container_config['image'] if run(f'podman image exists {image}') != 0: - Warning(f'Image "{image}" used in container "{name}" does not exist '\ - f'locally. Please use "add container image {image}" to add it '\ + Warning(f'Image "{image}" used in container "{name}" does not exist ' \ + f'locally. Please use "add container image {image}" to add it ' \ f'to the system! Container "{name}" will not be started!') if 'cpu_quota' in container_config: @@ -167,11 +172,11 @@ def verify(container): # We can not use the first IP address of a network prefix as this is used by podman if ip_address(address) == ip_network(network)[1]: - raise ConfigError(f'IP address "{address}" can not be used for a container, '\ + raise ConfigError(f'IP address "{address}" can not be used for a container, ' \ 'reserved for the container engine!') if cnt_ipv4 > 1 or cnt_ipv6 > 1: - raise ConfigError(f'Only one IP address per address family can be used for '\ + raise ConfigError(f'Only one IP address per address family can be used for ' \ f'container "{name}". {cnt_ipv4} IPv4 and {cnt_ipv6} IPv6 address(es)!') if 'device' in container_config: @@ -186,6 +191,13 @@ def verify(container): if not os.path.exists(source): raise ConfigError(f'Device "{dev}" source path "{source}" does not exist!') + if 'sysctl' in container_config and 'parameter' in container_config['sysctl']: + for var, cfg in container_config['sysctl']['parameter'].items(): + if 'value' not in cfg: + raise ConfigError(f'sysctl parameter {var} has no value assigned!') + if var.startswith('net.') and 'allow_host_networks' in container_config: + raise ConfigError(f'sysctl parameter {var} cannot be set when using host networking!') + if 'environment' in container_config: for var, cfg in container_config['environment'].items(): if 'value' not in cfg: @@ -219,7 +231,8 @@ def verify(container): # Can not set both allow-host-networks and network at the same time if {'allow_host_networks', 'network'} <= set(container_config): - raise ConfigError(f'"allow-host-networks" and "network" for "{name}" cannot be both configured at the same time!') + raise ConfigError( + f'"allow-host-networks" and "network" for "{name}" cannot be both configured at the same time!') # gid cannot be set without uid if 'gid' in container_config and 'uid' not in container_config: @@ -235,8 +248,10 @@ def verify(container): raise ConfigError(f'prefix for network "{network}" must be defined!') for prefix in network_config['prefix']: - if is_ipv4(prefix): v4_prefix += 1 - elif is_ipv6(prefix): v6_prefix += 1 + if is_ipv4(prefix): + v4_prefix += 1 + elif is_ipv6(prefix): + v6_prefix += 1 if v4_prefix > 1: raise ConfigError(f'Only one IPv4 prefix can be defined for network "{network}"!') @@ -262,6 +277,7 @@ def verify(container): return None + def generate_run_arguments(name, container_config): image = container_config['image'] cpu_quota = container_config['cpu_quota'] @@ -269,6 +285,12 @@ def generate_run_arguments(name, container_config): shared_memory = container_config['shared_memory'] restart = container_config['restart'] + # Add sysctl options + sysctl_opt = '' + if 'sysctl' in container_config and 'parameter' in container_config['sysctl']: + for k, v in container_config['sysctl']['parameter'].items(): + sysctl_opt += f" --sysctl {k}={v['value']}" + # Add capability options. Should be in uppercase capabilities = '' if 'capability' in container_config: @@ -341,7 +363,7 @@ def generate_run_arguments(name, container_config): if 'allow_host_pid' in container_config: host_pid = '--pid host' - container_base_cmd = f'--detach --interactive --tty --replace {capabilities} --cpus {cpu_quota} ' \ + container_base_cmd = f'--detach --interactive --tty --replace {capabilities} --cpus {cpu_quota} {sysctl_opt} ' \ f'--memory {memory}m --shm-size {shared_memory}m --memory-swap 0 --restart {restart} ' \ f'--name {name} {hostname} {device} {port} {volume} {env_opt} {label} {uid} {host_pid}' @@ -375,6 +397,7 @@ def generate_run_arguments(name, container_config): return f'{container_base_cmd} --no-healthcheck --net {networks} {ip_param} {entrypoint} {image} {command} {command_arguments}'.strip() + def generate(container): # bail out early - looks like removal from running config if not container: @@ -387,7 +410,7 @@ def generate(container): for network, network_config in container['network'].items(): tmp = { 'name': network, - 'id' : sha256(f'{network}'.encode()).hexdigest(), + 'id': sha256(f'{network}'.encode()).hexdigest(), 'driver': 'bridge', 'network_interface': f'pod-{network}', 'subnets': [], @@ -399,7 +422,7 @@ def generate(container): } } for prefix in network_config['prefix']: - net = {'subnet' : prefix, 'gateway' : inc_ip(prefix, 1)} + net = {'subnet': prefix, 'gateway': inc_ip(prefix, 1)} tmp['subnets'].append(net) if is_ipv6(prefix): @@ -418,11 +441,12 @@ def generate(container): file_path = os.path.join(systemd_unit_path, f'vyos-container-{name}.service') run_args = generate_run_arguments(name, container_config) - render(file_path, 'container/systemd-unit.j2', {'name': name, 'run_args': run_args,}, + render(file_path, 'container/systemd-unit.j2', {'name': name, 'run_args': run_args, }, formater=lambda _: _.replace(""", '"').replace("'", "'")) return None + def apply(container): # Delete old containers if needed. We can't delete running container # Option "--force" allows to delete containers with any status @@ -485,6 +509,7 @@ def apply(container): return None + if __name__ == '__main__': try: c = get_config() diff --git a/src/conf_mode/firewall.py b/src/conf_mode/firewall.py index e96e57154..ec6b86ef2 100755 --- a/src/conf_mode/firewall.py +++ b/src/conf_mode/firewall.py @@ -17,7 +17,6 @@ import os import re -from glob import glob from sys import exit from vyos.base import Warning @@ -33,6 +32,7 @@ from vyos.template import render from vyos.utils.dict import dict_search_args from vyos.utils.dict import dict_search_recursive from vyos.utils.process import call +from vyos.utils.process import cmd from vyos.utils.process import rc_cmd from vyos import ConfigError from vyos import airbag @@ -40,20 +40,7 @@ from vyos import airbag airbag.enable() nftables_conf = '/run/nftables.conf' - -sysfs_config = { - 'all_ping': {'sysfs': '/proc/sys/net/ipv4/icmp_echo_ignore_all', 'enable': '0', 'disable': '1'}, - 'broadcast_ping': {'sysfs': '/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts', 'enable': '0', 'disable': '1'}, - 'directed_broadcast' : {'sysfs': '/proc/sys/net/ipv4/conf/all/bc_forwarding', 'enable': '1', 'disable': '0'}, - 'ip_src_route': {'sysfs': '/proc/sys/net/ipv4/conf/*/accept_source_route'}, - 'ipv6_receive_redirects': {'sysfs': '/proc/sys/net/ipv6/conf/*/accept_redirects'}, - 'ipv6_src_route': {'sysfs': '/proc/sys/net/ipv6/conf/*/accept_source_route', 'enable': '0', 'disable': '-1'}, - 'log_martians': {'sysfs': '/proc/sys/net/ipv4/conf/all/log_martians'}, - 'receive_redirects': {'sysfs': '/proc/sys/net/ipv4/conf/*/accept_redirects'}, - 'send_redirects': {'sysfs': '/proc/sys/net/ipv4/conf/*/send_redirects'}, - 'syn_cookies': {'sysfs': '/proc/sys/net/ipv4/tcp_syncookies'}, - 'twa_hazards_protection': {'sysfs': '/proc/sys/net/ipv4/tcp_rfc1337'} -} +sysctl_file = r'/run/sysctl/10-vyos-firewall.conf' valid_groups = [ 'address_group', @@ -351,7 +338,7 @@ def verify(firewall): verify_nested_group(group_name, group, groups, []) if 'ipv4' in firewall: - for name in ['name','forward','input','output']: + for name in ['name','forward','input','output', 'prerouting']: if name in firewall['ipv4']: for name_id, name_conf in firewall['ipv4'][name].items(): if 'jump' in name_conf['default_action'] and 'default_jump_target' not in name_conf: @@ -371,7 +358,7 @@ def verify(firewall): verify_rule(firewall, rule_conf, False) if 'ipv6' in firewall: - for name in ['name','forward','input','output']: + for name in ['name','forward','input','output', 'prerouting']: if name in firewall['ipv6']: for name_id, name_conf in firewall['ipv6'][name].items(): if 'jump' in name_conf['default_action'] and 'default_jump_target' not in name_conf: @@ -467,33 +454,16 @@ def generate(firewall): local_zone_conf['from_local'][zone] = zone_conf['from'][local_zone] render(nftables_conf, 'firewall/nftables.j2', firewall) + render(sysctl_file, 'firewall/sysctl-firewall.conf.j2', firewall) return None -def apply_sysfs(firewall): - for name, conf in sysfs_config.items(): - paths = glob(conf['sysfs']) - value = None - - if name in firewall['global_options']: - conf_value = firewall['global_options'][name] - if conf_value in conf: - value = conf[conf_value] - elif conf_value == 'enable': - value = '1' - elif conf_value == 'disable': - value = '0' - - if value: - for path in paths: - with open(path, 'w') as f: - f.write(value) - def apply(firewall): install_result, output = rc_cmd(f'nft --file {nftables_conf}') if install_result == 1: raise ConfigError(f'Failed to apply firewall: {output}') - apply_sysfs(firewall) + # Apply firewall global-options sysctl settings + cmd(f'sysctl -f {sysctl_file}') call_dependents() diff --git a/src/conf_mode/load-balancing_reverse-proxy.py b/src/conf_mode/load-balancing_reverse-proxy.py index 09c68dadd..17226efe9 100755 --- a/src/conf_mode/load-balancing_reverse-proxy.py +++ b/src/conf_mode/load-balancing_reverse-proxy.py @@ -85,7 +85,7 @@ def verify(lb): raise ConfigError(f'"expect status" and "expect string" can not be configured together!') if 'health_check' in back_config: - if 'mode' not in back_config or back_config['mode'] != 'tcp': + if back_config['mode'] != 'tcp': raise ConfigError(f'backend "{back}" can only be configured with {back_config["health_check"]} ' + f'health-check whilst in TCP mode!') if 'http_check' in back_config: @@ -108,7 +108,7 @@ def verify(lb): # Check if http-response-headers are configured in any frontend/backend where mode != http for group in ['service', 'backend']: for config_name, config in lb[group].items(): - if 'http_response_headers' in config and ('mode' not in config or config['mode'] != 'http'): + if 'http_response_headers' in config and config['mode'] != 'http': raise ConfigError(f'{group} {config_name} must be set to http mode to use http_response_headers!') for front, front_config in lb['service'].items(): diff --git a/src/conf_mode/nat_cgnat.py b/src/conf_mode/nat_cgnat.py index bd6855e8b..cb336a35c 100755 --- a/src/conf_mode/nat_cgnat.py +++ b/src/conf_mode/nat_cgnat.py @@ -125,7 +125,19 @@ def generate_port_rules( port_count: int, global_port_range: str = '1024-65535', ) -> list: - """Generates list of nftables rules for the batch file.""" + """Generates a list of nftables option rules for the batch file. + + Args: + external_hosts (list): A list of external host IPs. + internal_hosts (list): A list of internal host IPs. + port_count (int): The number of ports required per host. + global_port_range (str): The global port range to be used. Default is '1024-65535'. + + Returns: + list: A list containing two elements: + - proto_map_elements (list): A list of proto map elements. + - other_map_elements (list): A list of other map elements. + """ rules = [] proto_map_elements = [] other_map_elements = [] @@ -134,13 +146,6 @@ def generate_port_rules( # Calculate the required number of ports per host required_ports_per_host = port_count - - # Check if there are enough external addresses for all internal hosts - if required_ports_per_host * len(internal_hosts) > total_possible_ports * len( - external_hosts - ): - raise ConfigError("Not enough ports available for the specified parameters!") - current_port = start_port current_external_index = 0 @@ -155,13 +160,6 @@ def generate_port_rules( current_port = start_port next_end_port = current_port + required_ports_per_host - 1 - # Ensure the same port is not assigned to the same external host - if any( - rule.endswith(f'{external_host}:{current_port}-{next_end_port}') - for rule in rules - ): - raise ConfigError("Not enough ports available for the specified parameters") - proto_map_elements.append( f'{internal_host} : {external_host} . {current_port}-{next_end_port}' ) @@ -254,6 +252,49 @@ def verify(config): used_external_pools[external_pool] = rule used_internal_pools[internal_pool] = rule + # Check calculation for allocation + external_port_range: str = config['pool']['external'][external_pool]['external_port_range'] + + external_ip_ranges: list = list( + config['pool']['external'][external_pool]['range'] + ) + internal_ip_ranges: list = config['pool']['internal'][internal_pool]['range'] + start_port, end_port = map(int, external_port_range.split('-')) + ports_per_range_count: int = (end_port - start_port) + 1 + + external_list_hosts_count = [] + external_list_hosts = [] + internal_list_hosts_count = [] + internal_list_hosts = [] + for ext_range in external_ip_ranges: + # External hosts count + e_count = IPOperations(ext_range).get_ips_count() + external_list_hosts_count.append(e_count) + # External hosts list + e_hosts = IPOperations(ext_range).convert_prefix_to_list_ips() + external_list_hosts.extend(e_hosts) + for int_range in internal_ip_ranges: + # Internal hosts count + i_count = IPOperations(int_range).get_ips_count() + internal_list_hosts_count.append(i_count) + # Internal hosts list + i_hosts = IPOperations(int_range).convert_prefix_to_list_ips() + internal_list_hosts.extend(i_hosts) + + external_host_count = sum(external_list_hosts_count) + internal_host_count = sum(internal_list_hosts_count) + ports_per_user: int = int( + config['pool']['external'][external_pool]['per_user_limit']['port'] + ) + users_per_extip = ports_per_range_count // ports_per_user + max_users = users_per_extip * external_host_count + + if internal_host_count > max_users: + raise ConfigError( + f'Rule "{rule}" does not have enough ports available for the ' + f'specified parameters' + ) + def generate(config): if not config: diff --git a/src/conf_mode/pki.py b/src/conf_mode/pki.py index 8deec0e85..f37cac524 100755 --- a/src/conf_mode/pki.py +++ b/src/conf_mode/pki.py @@ -67,6 +67,10 @@ sync_search = [ 'path': ['interfaces', 'sstpc'], }, { + 'keys': ['certificate', 'ca_certificate'], + 'path': ['load_balancing', 'reverse_proxy'], + }, + { 'keys': ['key'], 'path': ['protocols', 'rpki', 'cache'], }, diff --git a/src/conf_mode/system_conntrack.py b/src/conf_mode/system_conntrack.py index 031fe63b0..aa290788c 100755 --- a/src/conf_mode/system_conntrack.py +++ b/src/conf_mode/system_conntrack.py @@ -18,6 +18,7 @@ import os from sys import exit +from vyos.base import Warning from vyos.config import Config from vyos.configdep import set_dependents, call_dependents from vyos.utils.dict import dict_search @@ -165,6 +166,8 @@ def verify(conntrack): if not group_obj: Warning(f'{error_group} "{group_name}" has no members!') + Warning(f'It is prefered to define {inet} conntrack ignore rules in <firewall {inet} prerouting raw> section') + if dict_search_args(conntrack, 'timeout', 'custom', inet, 'rule') != None: for rule, rule_config in conntrack['timeout']['custom'][inet]['rule'].items(): if 'protocol' not in rule_config: diff --git a/src/migration-scripts/firewall/15-to-16 b/src/migration-scripts/firewall/15-to-16 new file mode 100755 index 000000000..7c8d38fe6 --- /dev/null +++ b/src/migration-scripts/firewall/15-to-16 @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# +# 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 +# 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/>. + +# T6394: Migrate conntrack timeout options to firewall global-options + # from: set system conntrack timeout .. + # to: set firewall global-options timeout ... + +from sys import argv +from sys import exit + +from vyos.configtree import ConfigTree + +if len(argv) < 2: + print("Must specify file name!") + exit(1) + +file_name = argv[1] + +with open(file_name, 'r') as f: + config_file = f.read() + +firewall_base = ['firewall', 'global-options'] +conntrack_base = ['system', 'conntrack', 'timeout'] +config = ConfigTree(config_file) + +if not config.exists(conntrack_base): + # Nothing to do + exit(0) + +for protocol in ['icmp', 'tcp', 'udp', 'other']: + if config.exists(conntrack_base + [protocol]): + if not config.exists(firewall_base): + config.set(firewall_base + ['timeout']) + config.copy(conntrack_base + [protocol], firewall_base + ['timeout', protocol]) + config.delete(conntrack_base + [protocol]) + +try: + with open(file_name, 'w') as f: + f.write(config.to_string()) +except OSError as e: + print("Failed to save the modified config: {}".format(e)) + exit(1)
\ No newline at end of file diff --git a/src/op_mode/cpu.py b/src/op_mode/cpu.py index d53663c17..1a0f7392f 100755 --- a/src/op_mode/cpu.py +++ b/src/op_mode/cpu.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # -# Copyright (C) 2016-2022 VyOS maintainers and contributors +# Copyright (C) 2016-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 @@ -16,8 +16,9 @@ import sys -import vyos.cpu import vyos.opmode +from vyos.utils.cpu import get_cpus +from vyos.utils.cpu import get_core_count from jinja2 import Template @@ -37,15 +38,15 @@ CPU model(s): {{models | join(", ")}} """) def _get_raw_data(): - return vyos.cpu.get_cpus() + return get_cpus() def _format_cpus(cpu_data): env = {'cpus': cpu_data} return cpu_template.render(env).strip() def _get_summary_data(): - count = vyos.cpu.get_core_count() - cpu_data = vyos.cpu.get_cpus() + count = get_core_count() + cpu_data = get_cpus() models = [c['model name'] for c in cpu_data] env = {'count': count, "models": models} @@ -79,4 +80,3 @@ if __name__ == '__main__': except (ValueError, vyos.opmode.Error) as e: print(e) sys.exit(1) - diff --git a/src/op_mode/ikev2_profile_generator.py b/src/op_mode/ikev2_profile_generator.py index 4ac4fb14a..169a15840 100755 --- a/src/op_mode/ikev2_profile_generator.py +++ b/src/op_mode/ikev2_profile_generator.py @@ -21,6 +21,10 @@ from socket import getfqdn from cryptography.x509.oid import NameOID from vyos.configquery import ConfigTreeQuery +from vyos.pki import CERT_BEGIN +from vyos.pki import CERT_END +from vyos.pki import find_chain +from vyos.pki import encode_certificate from vyos.pki import load_certificate from vyos.template import render_to_string from vyos.utils.io import ask_input @@ -146,27 +150,33 @@ data['rfqdn'] = '.'.join(tmp) pki = conf.get_config_dict(pki_base, get_first_key=True) cert_name = data['authentication']['x509']['certificate'] -data['certs'] = [] +cert_data = load_certificate(pki['certificate'][cert_name]['certificate']) +data['cert_common_name'] = cert_data.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value +data['ca_common_name'] = cert_data.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value +data['ca_certificates'] = [] -for ca_name in data['authentication']['x509']['ca_certificate']: - tmp = {} - ca_cert = load_certificate(pki['ca'][ca_name]['certificate']) - cert = load_certificate(pki['certificate'][cert_name]['certificate']) - - - tmp['ca_cn'] = ca_cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value - tmp['cert_cn'] = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value - tmp['ca_cert'] = conf.value(pki_base + ['ca', ca_name, 'certificate']) - - data['certs'].append(tmp) +loaded_ca_certs = {load_certificate(c['certificate']) + for c in pki['ca'].values()} if 'ca' in pki else {} +for ca_name in data['authentication']['x509']['ca_certificate']: + loaded_ca_cert = load_certificate(pki['ca'][ca_name]['certificate']) + ca_full_chain = find_chain(loaded_ca_cert, loaded_ca_certs) + for ca in ca_full_chain: + tmp = { + 'ca_name' : ca.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value, + 'ca_chain' : encode_certificate(ca).replace(CERT_BEGIN, '').replace(CERT_END, '').replace('\n', ''), + } + data['ca_certificates'].append(tmp) + +# Remove duplicate list entries for CA certificates, as they are added by their common name +# https://stackoverflow.com/a/9427216 +data['ca_certificates'] = [dict(t) for t in {tuple(d.items()) for d in data['ca_certificates']}] esp_proposals = conf.get_config_dict(ipsec_base + ['esp-group', data['esp_group'], 'proposal'], key_mangling=('-', '_'), get_first_key=True) ike_proposal = conf.get_config_dict(ipsec_base + ['ike-group', data['ike_group'], 'proposal'], key_mangling=('-', '_'), get_first_key=True) - # This script works only for Apple iOS/iPadOS and Windows. Both operating systems # have different limitations thus we load the limitations based on the operating # system used. diff --git a/src/op_mode/uptime.py b/src/op_mode/uptime.py index 059a4c3f6..559eed24c 100755 --- a/src/op_mode/uptime.py +++ b/src/op_mode/uptime.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 as @@ -29,8 +29,8 @@ def _get_uptime_seconds(): def _get_load_averages(): from re import search + from vyos.utils.cpu import get_core_count from vyos.utils.process import cmd - from vyos.cpu import get_core_count data = cmd("uptime") matches = search(r"load average:\s*(?P<one>[0-9\.]+)\s*,\s*(?P<five>[0-9\.]+)\s*,\s*(?P<fifteen>[0-9\.]+)\s*", data) |