diff options
Diffstat (limited to 'src')
47 files changed, 3728 insertions, 0 deletions
diff --git a/src/completion/list_disks.sh b/src/completion/list_disks.sh new file mode 100755 index 0000000..f32e558 --- /dev/null +++ b/src/completion/list_disks.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +# Completion script used by show disks to collect physical disk + +awk 'NR > 2 && $4 !~ /[0-9]$/ { print $4 }' </proc/partitions diff --git a/src/completion/list_dumpable_interfaces.py b/src/completion/list_dumpable_interfaces.py new file mode 100755 index 0000000..53ee896 --- /dev/null +++ b/src/completion/list_dumpable_interfaces.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 + +# Extract the list of interfaces available for traffic dumps from tcpdump -D + +import re +import subprocess + +if __name__ == '__main__': + out = subprocess.check_output(['/usr/sbin/tcpdump', '-D']).decode().strip() + out = out.split("\n") + + intfs = " ".join(map(lambda s: re.search(r'\d+\.(\S+)\s', s).group(1), out)) + + print(intfs) diff --git a/src/completion/list_interfaces.py b/src/completion/list_interfaces.py new file mode 100755 index 0000000..a4968c5 --- /dev/null +++ b/src/completion/list_interfaces.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +import sys +import argparse + +import vyos.interfaces + + +parser = argparse.ArgumentParser() +group = parser.add_mutually_exclusive_group() +group.add_argument("-t", "--type", type=str, help="List interfaces of specific type") +group.add_argument("-b", "--broadcast", action="store_true", help="List all broadcast interfaces") + +args = parser.parse_args() + +if args.type: + try: + interfaces = vyos.interfaces.list_interfaces_of_type(args.type) + + except ValueError as e: + print(e, file=sys.stderr) + print("") +elif args.broadcast: + eth = vyos.interfaces.list_interfaces_of_type("ethernet") + bridge = vyos.interfaces.list_interfaces_of_type("bridge") + bond = vyos.interfaces.list_interfaces_of_type("bonding") + interfaces = eth + bridge + bond +else: + interfaces = vyos.interfaces.list_interfaces() + +print(" ".join(interfaces)) diff --git a/src/completion/list_raidset.sh b/src/completion/list_raidset.sh new file mode 100755 index 0000000..9ff3523 --- /dev/null +++ b/src/completion/list_raidset.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +echo -n `cat /proc/partitions | grep md | awk '{ print $4 }'` diff --git a/src/conf_mode/bcast_relay.py b/src/conf_mode/bcast_relay.py new file mode 100755 index 0000000..95f6215 --- /dev/null +++ b/src/conf_mode/bcast_relay.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2017 VyOS maintainers and contributors +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 or later as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +# + +import sys +import os +import fnmatch +import subprocess + +from vyos.config import Config +from vyos import ConfigError + +config_file = r'/etc/default/udp-broadcast-relay' + +def get_config(): + conf = Config() + conf.set_level("service broadcast-relay id") + relay_id = conf.list_nodes("") + relays = [] + + for id in relay_id: + interface_list = [] + address = conf.return_value("{0} address".format(id)) + description = conf.return_value("{0} description".format(id)) + port = conf.return_value("{0} port".format(id)) + + # split the interface name listing and form a list + if conf.exists("{0} interface".format(id)): + intfs_names = [] + intfs_names = conf.return_values("{0} interface".format(id)) + + for name in intfs_names: + interface_list.append(name) + + relay = { + "id": id, + "address": address, + "description": description, + "interfaces" : interface_list, + "port": port + } + relays.append(relay) + + return relays + +def verify(relays): + for relay in relays: + if not relay["port"]: + raise ConfigError("UDP broadcast relay 'id {0}' requires a port number".format(relay["id"])) + + if len(relay["interfaces"]) < 2: + raise ConfigError("UDP broadcast relay 'id {0}' requires at least 2 interfaces".format(relay["id"])) + + return None + +def generate(relays): + config_header = '### Autogenerated by bcast_relay.py ###\n' + + config_dir = os.path.dirname(config_file) + config_filename = os.path.basename(config_file) + active_configs = [] + + for config in fnmatch.filter(os.listdir(config_dir), config_filename + '*'): + # determine prefix length to identify service instance + prefix_len = len(config_filename) + active_configs.append(config[prefix_len:]) + + # sort our list + active_configs.sort() + + for id in active_configs[:]: + os.unlink(config_file + id) + + for relay in relays: + file = config_file + str(relay["id"]) + interfaces = ' '.join(str(intf) for intf in relay["interfaces"]) + config_args = 'DAEMON_ARGS="{0} {1}"\n'.format(relay["port"], interfaces) + + f = open(file, 'w') + f.write(config_header) + if relay["description"]: + f.write('# ' + relay["description"] + '\n') + f.write(config_args) + f.close() + + return None + +def apply(relays): + # first stop all running services + cmd = "sudo systemctl stop udp-broadcast-relay@{1..99}" + os.system(cmd) + + # start only required service instances + for relay in relays: + cmd = "sudo systemctl start udp-broadcast-relay@{0}".format(relay["id"]) + os.system(cmd) + + return None + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/beep_if_fully_booted.py b/src/conf_mode/beep_if_fully_booted.py new file mode 100755 index 0000000..f00fcab --- /dev/null +++ b/src/conf_mode/beep_if_fully_booted.py @@ -0,0 +1,42 @@ +#!/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/>. +# +# + +import sys +import os + +from vyos.config import Config +from vyos import ConfigError + +def get_config(): + conf = Config() + if not conf.exists('system options beep-if-fully-booted'): + return None + + return True + +def apply(status): + if status is not None: + os.system('/usr/bin/beep -f 130 -l 100 -n -f 262 -l 100 -n -f 330 -l 100 -n -f 392 -l 100 -n -f 523 -l 100 -n -f 660 -l 100 -n -f 784 -l 300 -n -f 660 -l 300') + +if __name__ == '__main__': + try: + c = get_config() + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/dns_forwarding.py b/src/conf_mode/dns_forwarding.py new file mode 100755 index 0000000..d28e8ff --- /dev/null +++ b/src/conf_mode/dns_forwarding.py @@ -0,0 +1,234 @@ +#!/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/>. +# +# + +import sys +import os + +import netifaces +import jinja2 + +from vyos.config import Config +from vyos import ConfigError + +config_file = r'/etc/powerdns/recursor.conf' + +# XXX: pdns recursor doesn't like whitespace near entry separators, +# especially in the semicolon-separated lists of name servers. +# Please be careful if you edit the template. +config_tmpl = """ +### Autogenerated by dns_forwarding.py ### + +# Non-configurable defaults +daemon=yes +threads=1 +allow-from=0.0.0.0/0 +log-common-errors=yes +non-local-bind=yes + +# cache-size +max-cache-entries={{ cache_size }} + +# negative TTL for NXDOMAIN +max-negative-ttl={{ negative_ttl }} + +# ignore-hosts-file +export-etc-hosts={{ export_hosts_file }} + +# listen-on +local-address={{ listen_on | join(',') }} + +# domain ... server ... +{% if domains -%} + +forward-zones={% for d in domains %} +{{ d.name }}={{ d.servers | join(";") }} +{{- "," if not loop.last -}} +{% endfor %} + +{% endif %} + +# name-server +forward-zones-recurse=.={{ name_servers | join(';') }} + +""" + +default_config_data = { + 'cache_size': 10000, + 'export_hosts_file': 'yes', + 'listen_on': [], + 'interfaces': [], + 'name_servers': [], + 'negative_ttl': 3600, + 'domains': [] +} + + +# borrowed from: https://github.com/donjajo/py-world/blob/master/resolvconfReader.py, THX! +def get_resolvers(file): + resolvers = [] + try: + with open(file, 'r') as resolvconf: + for line in resolvconf.readlines(): + line = line.split('#',1)[0]; + line = line.rstrip(); + if 'nameserver' in line: + resolvers.append(line.split()[1]) + return resolvers + except IOError: + return [] + +def get_config(): + dns = default_config_data + conf = Config() + if not conf.exists('service dns forwarding'): + return None + else: + conf.set_level('service dns forwarding') + + if conf.exists('cache-size'): + cache_size = conf.return_value('cache-size') + dns['cache_size'] = cache_size + + if conf.exists('negative-ttl'): + negative_ttl = conf.return_value('negative-ttl') + dns['negative_ttl'] = negative_ttl + + if conf.exists('domain'): + for node in conf.list_nodes('domain'): + server = conf.return_values("domain {0} server".format(node)) + domain = { + "name": node, + "servers": server + } + dns['domains'].append(domain) + + if conf.exists('ignore-hosts-file'): + dns['export_hosts_file'] = "no" + + if conf.exists('name-server'): + name_servers = conf.return_values('name-server') + dns['name_servers'] = dns['name_servers'] + name_servers + + if conf.exists('system'): + conf.set_level('system') + system_name_servers = [] + system_name_servers = conf.return_values('name-server') + if not system_name_servers: + print("DNS forwarding warning: No name-servers set under 'system name-server'\n") + else: + dns['name_servers'] = dns['name_servers'] + system_name_servers + conf.set_level('service dns forwarding') + + if conf.exists('listen-address'): + dns['listen_on'] = conf.return_values('listen-address') + + ## Hacks and tricks + + # The old VyOS syntax that comes from dnsmasq was "listen-on $interface". + # pdns wants addresses instead, so we emulate it by looking up all addresses + # of a given interface and writing them to the config + if conf.exists('listen-on'): + print("WARNING: since VyOS 1.2.0, \"service dns forwarding listen-on\" is a limited compatibility option.") + print("It will only make DNS forwarder listen on addresses assigned to the interface at the time of commit") + print("which means it will NOT work properly with VRRP/clustering or addresses received from DHCP.") + print("Please reconfigure your system with \"service dns forwarding listen-address\" instead.") + + interfaces = conf.return_values('listen-on') + + listen4 = [] + listen6 = [] + for interface in interfaces: + try: + addrs = netifaces.ifaddresses(interface) + except ValueError: + print("WARNING: interface {0} does not exist".format(interface)) + continue + + if netifaces.AF_INET in addrs.keys(): + for ip4 in addrs[netifaces.AF_INET]: + listen4.append(ip4['addr']) + + if netifaces.AF_INET6 in addrs.keys(): + for ip6 in addrs[netifaces.AF_INET6]: + listen6.append(ip6['addr']) + + if (not listen4) and (not (listen6)): + print("WARNING: interface {0} has no configured addresses".format(interface)) + + dns['listen_on'] = dns['listen_on'] + listen4 + listen6 + + # Save interfaces in the dict for the reference + dns['interfaces'] = interfaces + + # Add name servers received from DHCP + if conf.exists('dhcp'): + interfaces = [] + interfaces = conf.return_values('dhcp') + for interface in interfaces: + dhcp_resolvers = get_resolvers("/etc/resolv.conf.dhclient-new-{0}".format(interface)) + if dhcp_resolvers: + dns['name_servers'] = dns['name_servers'] + dhcp_resolvers + + return dns + +def verify(dns): + # bail out early - looks like removal from running config + if dns is None: + return None + + if not dns['listen_on']: + raise ConfigError("Error: DNS forwarding requires either a listen-address (preferred) or a listen-on option") + + if dns['domains']: + for domain in dns['domains']: + if not domain['servers']: + raise ConfigError('Error: No server configured for domain {0}'.format(domain['name'])) + + return None + +def generate(dns): + # bail out early - looks like removal from running config + if dns is None: + return None + + tmpl = jinja2.Template(config_tmpl, trim_blocks=True) + + config_text = tmpl.render(dns) + with open(config_file, 'w') as f: + f.write(config_text) + return None + +def apply(dns): + if dns is not None: + os.system("systemctl restart pdns-recursor") + else: + # DNS forwarding is removed in the commit + os.system("systemctl stop pdns-recursor") + os.unlink(config_file) + + return None + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/host_name.py b/src/conf_mode/host_name.py new file mode 100755 index 0000000..3b3958f --- /dev/null +++ b/src/conf_mode/host_name.py @@ -0,0 +1,117 @@ +#!/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/>. +# +# + +""" +conf-mode script for 'system host-name' and 'system domain-name'. +""" + +import os +import re +import sys +import subprocess + +from vyos.config import Config +from vyos import ConfigError + + +hosts_file = '/etc/hosts' +hostname_regex = re.compile("^[A-Za-z0-9][-.A-Za-z0-9]*[A-Za-z0-9]$") +local_addr = '127.0.1.1' # NOSONAR + + +def get_config(): + """Get configuration""" + conf = Config() + + hostname = conf.return_value("system host-name") + domain = conf.return_value("system domain-name") + + # No one likes fixups, but we really don't want VyOS fail to boot + # if hostname is not in the config + if not hostname: + hostname = "vyos" + + if domain: + fqdn = "{0}.{1}".format(hostname, domain) + else: + fqdn = hostname + + return {"hostname": hostname, "domain": domain, "fqdn": fqdn} + + +def verify(config): + """Verify configuration""" + # check for invalid host + + # pattern $VAR(@) "^[[:alnum:]][-.[:alnum:]]*[[:alnum:]]$" ; "invalid host name $VAR(@)" + if not hostname_regex.match(config["hostname"]): + raise ConfigError('Invalid host name ' + config["hostname"]) + + # pattern $VAR(@) "^.{1,63}$" ; "invalid host-name length" + length = len(config["hostname"]) + if length < 1 or length > 63: + raise ConfigError( + 'Invalid host-name length, must be less than 63 characters') + + return None + + +def generate(config): + """Generate configuration files""" + # read the hosts file + with open(hosts_file, 'r') as f: + hosts = f.read() + + # get the current hostname + old_hostname = subprocess.check_output(['hostname']).decode().strip() + + # replace the local host line + vyos_host_line_re = re.compile(r"({}\s+{}.*)".format(local_addr, old_hostname)) + vyos_host_line = "{}\t{} # VyOS entry\n".format(local_addr, config["fqdn"]) + if re.search(vyos_host_line_re, hosts): + hosts = re.sub(vyos_host_line_re, vyos_host_line, hosts) + else: + # On boot (or after errors), the /etc/hosts file has no line for vyos hostname, + # so we have to add it + hosts = "{0}\n{1}".format(hosts, vyos_host_line) + + with open(hosts_file, 'w') as f: + f.write(hosts) + + return None + + +def apply(config): + """Apply configuration""" + os.system("hostnamectl set-hostname --static {0}".format(config["fqdn"])) + + # restart services that use the hostname + os.system("systemctl restart rsyslog.service") + + return None + + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/lldp.py b/src/conf_mode/lldp.py new file mode 100644 index 0000000..27749c8 --- /dev/null +++ b/src/conf_mode/lldp.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2017 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 re +import sys + +from vyos.config import Config +from vyos import ConfigError + + +def get_options(config): + options = {} + config.set_level('service lldp') + options['listen_vlan'] = config.exists('listen-vlan') + + options["addr"] = config.return_value('management-address') + + snmp = config.exists('snmp enable') + options["snmp"] = snmp + if snmp: + config.set_level('') + options["sys_snmp"] = config.exists('service snmp') + config.set_level('service lldp') + + config.set_level('service lldp legacy-protocols') + options["cdp"] = config.exists("cdp") + options["edp"] = config.exists("edp") + options["fdp"] = config.exists("fdp") + options["sonmp"] = config.exists("sonmp") + return options + + +def get_interface_list(config): + config.set_level('service lldp') + intfs_names = config.list_nodes('interface') + if len(intfs_names) < 0: + return 0 + interface_list = [] + for name in intfs_names: + config.set_level("service lldp interface {0}".format(name)) + disable = config.exists('disable') + intf = { + "name": name, + "disable": disable + } + interface_list.append(intf) + return interface_list + + +def get_location_intf(config, name): + path = "service lldp interface {0}".format(name) + config.set_level(path) + if config.exists("location"): + return 0 + config.set_level("{} location".format(path)) + civic_based = {} + elin = None + coordinate_based = {} + + if config.exists('civic-based'): + config.set_level("{} location civic-based".format(path)) + cc = config.return_value("country-code") + civic_based["country_code"] = cc + civic_based["ca_type"] = [] + ca_types_names = config.list_nodes('ca-type') + if ca_types_names: + for ca_types_name in ca_types_names: + config.set_level("{0} location civic-based ca-type {1}".format(path, ca_types_name)) + ca_val = config.return_value('ca-value') + ca_type = { + "name": ca_types_name, + "ca_val": ca_val + } + civic_based["ca_type"].append(ca_type) + + elif config.exists("elin"): + elin = config.return_value("elin") + + elif config.exists("coordinate-based"): + config.set_level("{} location coordinate-based".format(path)) + alt = config.return_value("altitude") + lat = config.return_value("latitude") + long = config.return_value("longitude") + datum = config.return_value("datum") + coordinate_based["altitude"] = alt + coordinate_based["latitude"] = lat + coordinate_based["longitude"] = long + coordinate_based["datum"] = datum + + intf = { + "name": name, + "civic_based": civic_based, + "elin": elin, + "coordinate_based": coordinate_based + + } + return intf + + +def get_location(config): + config.set_level('service lldp') + intfs_names = config.list_nodes('interface') + if len(intfs_names) < 0: + return 0 + if config.exists("disable"): + return 0 + intfs_location = [] + for name in intfs_names: + intf = get_location_intf(config, name) + intfs_location.append(intf) + return intfs_location + + +def get_config(): + conf = Config() + options = get_options(conf) + interface_list = get_interface_list(conf) + location = get_location(conf) + lldp = {"options": options, "interface_list": interface_list, "location": location} + return lldp + + +def verify(lldp): + + # check location + for location in lldp["location"]: + + # check civic-based + if len(location["civic_based"]) > 0: + if len(location["coordinate_based"]) > 0 or location["elin"]: + raise ConfigError("Can only configure 1 location type for interface {0}".format(location["name"])) + + # check country-code + if not location["civic_based"]["country_code"]: + raise ConfigError("Invalid location for interface {0}: must configure the country code".format(location["name"])) + + if not re.match(r"^[a-zA-Z]{2}$", location["civic_based"]["country_code"]): + raise ConfigError("Invalid location for interface {0}: country-code must be 2 characters".format(location["name"])) + # check ca-type + if len(location["civic_based"]["ca_type"]) < 0: + raise ConfigError("Invalid location for interface {0}: must define at least 1 ca-type".format(location["name"])) + + for ca_type in location["civic_based"]["ca_type"]: + if not int(ca_type["name"]) in range(0, 129): + raise ConfigError("Invalid location for interface {0}: ca-type must between 0-128".format(location["name"])) + + if not ca_type["ca_val"]: + raise ConfigError("Invalid location for interface {0}: must configure the ca-value for ca-type {1}".format(location["name"],ca_type["name"])) + + # check coordinate-based + elif len(location["coordinate_based"]) > 0: + # check longitude and latitude + if not location["coordinate_based"]["longitude"]: + raise ConfigError("Must define longitude for interface {0}".format(location["name"])) + + if not location["coordinate_based"]["latitude"]: + raise ConfigError("Must define latitude for interface {0}".format(location["name"])) + + if not re.match(r"^(\d+)(\.\d+)?[nNsS]$", location["coordinate_based"]["latitude"]): + raise ConfigError("Invalid location for interface {0}: latitude should be a number followed by S or N".format(location["name"])) + + if not re.match(r"^(\d+)(\.\d+)?[eEwW]$", location["coordinate_based"]["longitude"]): + raise ConfigError("Invalid location for interface {0}: longitude should be a number followed by E or W".format(location["name"])) + + # check altitude and datum if exist + if location["coordinate_based"]["altitude"]: + if not re.match(r"^[-+0-9\.]+$", location["coordinate_based"]["altitude"]): + raise ConfigError("Invalid location for interface {0}: altitude should be a positive or negative number".format(location["name"])) + + if location["coordinate_based"]["datum"]: + if not re.match(r"^(WGS84|NAD83|MLLW)$", location["coordinate_based"]["datum"]): + raise ConfigError("Invalid location for interface {0}: datum should be WGS84, NAD83, or MLLW".format(location["name"])) + + # check elin + elif len(location["elin"]) > 0: + if not re.match(r"^[0-9]{10,25}$", location["elin"]): + raise ConfigError("Invalid location for interface {0}: ELIN number must be between 10-25 numbers".format(location["name"])) + + # check options + if lldp["options"]["snmp"]: + if not lldp["options"]["sys_snmp"]: + raise ConfigError("SNMP must be configured to enable LLDP SNMP") + + +def generate(config): + pass + + +def apply(config): + pass + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) + diff --git a/src/conf_mode/mdns_repeater.py b/src/conf_mode/mdns_repeater.py new file mode 100755 index 0000000..474a6a5 --- /dev/null +++ b/src/conf_mode/mdns_repeater.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2017 VyOS maintainers and contributors +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 or later as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +# + +import sys +import os + +import netifaces + +from vyos.config import Config +from vyos import ConfigError + +config_file = r'/etc/default/mdns-repeater' + +def get_config(): + interface_list = [] + + conf = Config() + conf.set_level('service mdns repeater') + if not conf.exists(''): + return interface_list + + if conf.exists('interface'): + intfs_names = [] + intfs_names = conf.return_values('interface') + + for name in intfs_names: + interface_list.append(name) + + return interface_list + +def verify(mdns): + # '0' interfaces are possible, think of service deletion. Only '1' is not supported! + if len(mdns) == 1: + raise ConfigError('At least 2 interfaces must be specified but %d given!' % len(mdns)) + + # For mdns-repeater to work it is essential that the interfaces + # have an IP address assigned + for intf in mdns: + try: + netifaces.ifaddresses(intf)[netifaces.AF_INET] + except KeyError as e: + raise ConfigError('No IP address configured for interface "%s"!' % intf) + + return None + +def generate(mdns): + config_header = '### Autogenerated by mdns_repeater.py ###\n' + if len(mdns) > 0: + config_args = 'DAEMON_ARGS="' + ' '.join(str(e) for e in mdns) + '"\n' + else: + config_args = 'DAEMON_ARGS=""\n' + + # write new configuration file + f = open(config_file, 'w') + f.write(config_header) + f.write(config_args) + f.close() + + return None + +def apply(mdns): + if len(mdns) == 0: + cmd = "sudo systemctl stop mdns-repeater" + else: + cmd = "sudo systemctl restart mdns-repeater" + + os.system(cmd) + return None + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/ntp.py b/src/conf_mode/ntp.py new file mode 100755 index 0000000..2a60885 --- /dev/null +++ b/src/conf_mode/ntp.py @@ -0,0 +1,173 @@ +#!/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/>. +# +# + +import sys +import os + +import jinja2 +import ipaddress + +from vyos.config import Config +from vyos import ConfigError + +config_file = r'/etc/ntp.conf' + +# Please be careful if you edit the template. +config_tmpl = """ +### Autogenerated by ntp.py ### + +# +# Non-configurable defaults +# +driftfile /var/lib/ntp/ntp.drift +# By default, only allow ntpd to query time sources, ignore any incoming requests +restrict default ignore +# Local users have unrestricted access, allowing reconfiguration via ntpdc +restrict 127.0.0.1 +restrict -6 ::1 + + +# +# Configurable section +# + +{% if servers -%} +{% for s in servers -%} +# Server configuration for: {{ s.name }} +server {{ s.name }} iburst {{ s.options | join(" ") }} + +{% endfor -%} +{% endif %} + +{% if allowed_networks -%} +{% for n in allowed_networks -%} +# Client configuration for network: {{ n.network }} +restrict {{ n.address }} mask {{ n.netmask }} nomodify notrap nopeer + +{% endfor -%} +{% endif %} + +{% if listen_address -%} +# NTP should listen on configured addresses only +interface ignore wildcard +{% for a in listen_address -%} +interface listen {{ a }} +{% endfor -%} +{% endif %} + +""" + +default_config_data = { + 'servers': [], + 'allowed_networks': [], + 'listen_address': [] +} + +def get_config(): + ntp = default_config_data + conf = Config() + if not conf.exists('system ntp'): + return None + else: + conf.set_level('system ntp') + + if conf.exists('allow-clients address'): + networks = conf.return_values('allow-clients address') + for n in networks: + addr = ipaddress.ip_network(n) + net = { + "network" : n, + "address" : addr.network_address, + "netmask" : addr.netmask + } + + ntp['allowed_networks'].append(net) + + if conf.exists('listen-address'): + ntp['listen_address'] = conf.return_values('listen-address') + + if conf.exists('server'): + for node in conf.list_nodes('server'): + options = [] + server = { + "name": node, + "options": [] + } + if conf.exists('server {0} dynamic'.format(node)): + options.append('dynamic') + if conf.exists('server {0} noselect'.format(node)): + options.append('noselect') + if conf.exists('server {0} preempt'.format(node)): + options.append('preempt') + if conf.exists('server {0} prefer'.format(node)): + options.append('prefer') + + server['options'] = options + ntp['servers'].append(server) + + return ntp + +def verify(ntp): + # bail out early - looks like removal from running config + if ntp is None: + return None + + # Configuring allowed clients without a server makes no sense + if len(ntp['allowed_networks']) and not len(ntp['servers']): + raise ConfigError('NTP server not configured') + + for n in ntp['allowed_networks']: + try: + addr = ipaddress.ip_network( n['network'] ) + break + except ValueError: + raise ConfigError("{0} does not appear to be a valid IPv4 or IPv6 network, check host bits!".format(n['network'])) + + return None + +def generate(ntp): + # bail out early - looks like removal from running config + if ntp is None: + return None + + tmpl = jinja2.Template(config_tmpl) + config_text = tmpl.render(ntp) + with open(config_file, 'w') as f: + f.write(config_text) + + return None + +def apply(ntp): + if ntp is not None: + os.system('sudo /usr/sbin/invoke-rc.d ntp force-reload') + else: + # NTP suuport is removed in the commit + os.system('sudo /usr/sbin/invoke-rc.d ntp stop') + os.unlink(config_file) + + return None + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/snmp.py b/src/conf_mode/snmp.py new file mode 100755 index 0000000..1590e5d --- /dev/null +++ b/src/conf_mode/snmp.py @@ -0,0 +1,804 @@ +#!/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/>. +# +# + +import sys +import os +import shutil +import stat +import pwd +import time + +import jinja2 +import ipaddress +import random +import binascii +import re + +import vyos.version + +from vyos.config import Config +from vyos import ConfigError + +config_file_client = r'/etc/snmp/snmp.conf' +config_file_daemon = r'/etc/snmp/snmpd.conf' +config_file_access = r'/usr/share/snmp/snmpd.conf' +config_file_user = r'/var/lib/snmp/snmpd.conf' + +# SNMP OIDs used to mark auth/priv type +OIDs = { + 'md5' : '.1.3.6.1.6.3.10.1.1.2', + 'sha' : '.1.3.6.1.6.3.10.1.1.3', + 'aes' : '.1.3.6.1.6.3.10.1.2.4', + 'des' : '.1.3.6.1.6.3.10.1.2.2', + 'none': '.1.3.6.1.6.3.10.1.2.1' +} +# SNMPS template - be careful if you edit the template. +client_config_tmpl = """ +### Autogenerated by snmp.py ### +{% if trap_source -%} +clientaddr {{ trap_source }} +{% endif %} + +""" + +# SNMPS template - be careful if you edit the template. +access_config_tmpl = """ +### Autogenerated by snmp.py ### +{% if v3_users %} +{% for u in v3_users %} +{{ u.mode }}user {{ u.name }} +{% endfor %} +{% endif -%} +rwuser {{ vyos_user }} + +""" + +# SNMPS template - be careful if you edit the template. +user_config_tmpl = """ +### Autogenerated by snmp.py ### +# user +{% if v3_users %} +{% for u in v3_users %} +{% if u.authOID == 'none' %} +createUser {{ u.name }} +{% elif u.authPassword %} +createUser {{ u.name }} {{ u.authProtocol | upper }} "{{ u.authPassword }}" {{ u.privProtocol | upper }} {{ u.privPassword }} +{% else %} +usmUser 1 3 {{ u.engineID }} "{{ u.name }}" "{{ u.name }}" NULL {{ u.authOID }} {{ u.authMasterKey }} {{ u.privOID }} {{ u.privMasterKey }} 0x +{% endif %} +{% endfor %} +{% endif %} + +createUser {{ vyos_user }} MD5 "{{ vyos_user_pass }}" DES +""" + +# SNMPS template - be careful if you edit the template. +daemon_config_tmpl = """ +### Autogenerated by snmp.py ### + +# non configurable defaults +sysObjectID 1.3.6.1.4.1.44641 +sysServices 14 +master agentx +agentXPerms 0755 0755 +pass .1.3.6.1.2.1.31.1.1.1.18 /opt/vyatta/sbin/if-mib-alias +smuxpeer .1.3.6.1.2.1.83 +smuxpeer .1.3.6.1.2.1.157 +smuxpeer .1.3.6.1.4.1.3317.1.2.2 +smuxpeer .1.3.6.1.4.1.3317.1.2.3 +smuxpeer .1.3.6.1.4.1.3317.1.2.5 +smuxpeer .1.3.6.1.4.1.3317.1.2.8 +smuxpeer .1.3.6.1.4.1.3317.1.2.9 +smuxsocket localhost + +# linkUp/Down configure the Event MIB tables to monitor +# the ifTable for network interfaces being taken up or down +# for making internal queries to retrieve any necessary information +iquerySecName {{ vyos_user }} + +# Modified from the default linkUpDownNotification +# to include more OIDs and poll more frequently +notificationEvent linkUpTrap linkUp ifIndex ifDescr ifType ifAdminStatus ifOperStatus +notificationEvent linkDownTrap linkDown ifIndex ifDescr ifType ifAdminStatus ifOperStatus +monitor -r 10 -e linkUpTrap "Generate linkUp" ifOperStatus != 2 +monitor -r 10 -e linkDownTrap "Generate linkDown" ifOperStatus == 2 + +######################## +# configurable section # +######################## + +{% if v3_tsm_key %} +[snmp] localCert {{ v3_tsm_key }} +{% endif %} + +# Default system description is VyOS version +sysDescr VyOS {{ version }} + +{% if description -%} +# Description +SysDescr {{ description }} +{% endif %} + +# Listen +agentaddress unix:/run/snmpd.socket{% if listen_on %}{% for li in listen_on %},{{ li }}{% endfor %}{% else %},udp:161,udp6:161{% endif %}{% if v3_tsm_key %},tlstcp:{{ v3_tsm_port }},dtlsudp::{{ v3_tsm_port }}{% endif %} + + +# SNMP communities +{% if communities -%} +{% for c in communities %} +{% if c.network -%} +{% for network in c.network %} +{{ c.authorization }}community {{ c.name }} {{ network }} +{% endfor %} +{% else %} +{{ c.authorization }}community {{ c.name }} +{% endif %} +{% endfor %} +{% endif %} + +{% if contact -%} +# system contact information +SysContact {{ contact }} +{% endif %} + +{% if location -%} +# system location information +SysLocation {{ location }} +{% endif %} + +{% if smux_peers -%} +# additional smux peers +{% for sp in smux_peers %} +smuxpeer {{ sp }} +{% endfor %} +{% endif %} + +{% if trap_targets -%} +# if there is a problem - tell someone! +{% for t in trap_targets %} +trap2sink {{ t.target }}{% if t.port -%}:{{ t.port }}{% endif %} {{ t.community }} +{% endfor %} +{% endif %} + +# +# SNMPv3 stuff goes here +# +{% if v3_enabled %} + +# views +{% if v3_views -%} +{% for v in v3_views %} +{% for oid in v.oids %} +view {{ v.name }} included .{{ oid.oid }} +{% endfor %} +{% endfor %} +{% endif %} + +# access +# context sec.model sec.level match read write notif +{% if v3_groups -%} +{% for g in v3_groups %} +{% if g.mode == 'ro' %} +access {{ g.name }} "" usm {{ g.seclevel }} exact {{ g.view }} none none +access {{ g.name }} "" tsm {{ g.seclevel }} exact {{ g.view }} none none +{% elif g.mode == 'rw' %} +access {{ g.name }} "" usm {{ g.seclevel }} exact {{ g.view }} {{ g.view }} none +access {{ g.name }} "" tsm {{ g.seclevel }} exact {{ g.view }} {{ g.view }} none +{% endif %} +{% endfor -%} +{% endif %} + +# trap-target +{% if v3_traps -%} +{% for t in v3_traps %} +trapsess -v 3 {{ '-Ci' if t.type == 'inform' }} -e {{ t.engineID }} -u {{ t.secName }} -l {{ t.secLevel }} -a {{ t.authProtocol }} {% if t.authPassword %}-A {{ t.authPassword }}{% elif t.authMasterKey %}-3m {{ t.authMasterKey }}{% endif %} -x {{ t.privProtocol }} {% if t.privPassword %}-X {{ t.privPassword }}{% elif t.privMasterKey %}-3M {{ t.privMasterKey }}{% endif %} {{ t.ipProto }}:{{ t.ipAddr }}:{{ t.ipPort }} +{% endfor -%} +{% endif %} + +# group +{% if v3_users -%} +{% for u in v3_users %} +group {{ u.group }} usm {{ u.name }} +group {{ u.group }} tsm {{ u.name }} +{% endfor %} +{% endif %} + +{% endif %} + +""" + +default_config_data = { + 'listen_on': [], + 'communities': [], + 'smux_peers': [], + 'location' : '', + 'description' : '', + 'contact' : '', + 'trap_source': '', + 'trap_targets': [], + 'vyos_user': '', + 'vyos_user_pass': '', + 'version': '999', + 'v3_enabled': 'False', + 'v3_engineid': '', + 'v3_groups': [], + 'v3_traps': [], + 'v3_tsm_key': '', + 'v3_tsm_port': '10161', + 'v3_users': [], + 'v3_views': [] +} + +def rmfile(file): + if os.path.isfile(file): + os.unlink(file) + +def get_config(): + snmp = default_config_data + conf = Config() + if not conf.exists('service snmp'): + return None + else: + conf.set_level('service snmp') + + version_data = vyos.version.get_version_data() + snmp['version'] = version_data['version'] + + # create an internal snmpv3 user of the form 'vyattaxxxxxxxxxxxxxxxx' + # os.urandom(8) returns 8 bytes of random data + snmp['vyos_user'] = 'vyatta' + binascii.hexlify(os.urandom(8)).decode('utf-8') + snmp['vyos_user_pass'] = binascii.hexlify(os.urandom(16)).decode('utf-8') + + if conf.exists('community'): + for name in conf.list_nodes('community'): + community = { + 'name': name, + 'authorization': 'ro', + 'network': [] + } + + if conf.exists('community {0} authorization'.format(name)): + community['authorization'] = conf.return_value('community {0} authorization'.format(name)) + + if conf.exists('community {0} network'.format(name)): + community['network'] = conf.return_values('community {0} network'.format(name)) + + snmp['communities'].append(community) + + if conf.exists('contact'): + snmp['contact'] = conf.return_value('contact') + + if conf.exists('description'): + snmp['description'] = conf.return_value('description') + + if conf.exists('listen-address'): + for addr in conf.list_nodes('listen-address'): + listen = '' + port = '161' + if conf.exists('listen-address {0} port'.format(addr)): + port = conf.return_value('listen-address {0} port'.format(addr)) + + if ipaddress.ip_address(addr).version == 4: + # udp:127.0.0.1:161 + listen = 'udp:' + addr + ':' + port + elif ipaddress.ip_address(addr).version == 6: + # udp6:[::1]:161 + listen = 'udp6:' + '[' + addr + ']' + ':' + port + else: + raise ConfigError('Invalid IP address version') + + snmp['listen_on'].append(listen) + + if conf.exists('location'): + snmp['location'] = conf.return_value('location') + + if conf.exists('smux-peer'): + snmp['smux_peers'] = conf.return_values('smux-peer') + + if conf.exists('trap-source'): + snmp['trap_source'] = conf.return_value('trap-source') + + if conf.exists('trap-target'): + for target in conf.list_nodes('trap-target'): + trap_tgt = { + 'target': target, + 'community': '', + 'port': '' + } + + if conf.exists('trap-target {0} community'.format(target)): + trap_tgt['community'] = conf.return_value('trap-target {0} community'.format(target)) + + if conf.exists('trap-target {0} port'.format(target)): + trap_tgt['port'] = conf.return_value('trap-target {0} port'.format(target)) + + snmp['trap_targets'].append(trap_tgt) + + ######################################################################### + # ____ _ _ __ __ ____ _____ # + # / ___|| \ | | \/ | _ \ __ _|___ / # + # \___ \| \| | |\/| | |_) | \ \ / / |_ \ # + # ___) | |\ | | | | __/ \ V / ___) | # + # |____/|_| \_|_| |_|_| \_/ |____/ # + # # + # now take care about the fancy SNMP v3 stuff, or bail out eraly # + ######################################################################### + if not conf.exists('v3'): + return snmp + else: + snmp['v3_enabled'] = True + + # + # 'set service snmp v3 engineid' + # + if conf.exists('v3 engineid'): + snmp['v3_engineid'] = conf.return_value('v3 engineid') + + # + # 'set service snmp v3 group' + # + if conf.exists('v3 group'): + for group in conf.list_nodes('v3 group'): + v3_group = { + 'name': group, + 'mode': 'ro', + 'seclevel': 'auth', + 'view': '' + } + + if conf.exists('v3 group {0} mode'.format(group)): + v3_group['mode'] = conf.return_value('v3 group {0} mode'.format(group)) + + if conf.exists('v3 group {0} seclevel'.format(group)): + v3_group['seclevel'] = conf.return_value('v3 group {0} seclevel'.format(group)) + + if conf.exists('v3 group {0} view'.format(group)): + v3_group['view'] = conf.return_value('v3 group {0} view'.format(group)) + + snmp['v3_groups'].append(v3_group) + + # + # 'set service snmp v3 trap-target' + # + if conf.exists('v3 trap-target'): + for trap in conf.list_nodes('v3 trap-target'): + trap_cfg = { + 'ipAddr': trap, + 'engineID': '', + 'secName': '', + 'authProtocol': 'md5', + 'authPassword': '', + 'authMasterKey': '', + 'privProtocol': 'des', + 'privPassword': '', + 'privMasterKey': '', + 'ipProto': 'udp', + 'ipPort': '162', + 'type': '', + 'secLevel': 'noAuthNoPriv' + } + + if conf.exists('v3 trap-target {0} engineid'.format(trap)): + # Set the context engineID used for SNMPv3 REQUEST messages scopedPdu. + # If not specified, this will default to the authoritative engineID. + trap_cfg['engineID'] = conf.return_value('v3 trap-target {0} engineid'.format(trap)) + + if conf.exists('v3 trap-target {0} user'.format(trap)): + # Set the securityName used for authenticated SNMPv3 messages. + trap_cfg['secName'] = conf.return_value('v3 trap-target {0} user'.format(trap)) + + if conf.exists('v3 trap-target {0} auth type'.format(trap)): + # Set the authentication protocol (MD5 or SHA) used for authenticated SNMPv3 messages + # cmdline option '-a' + trap_cfg['authProtocol'] = conf.return_value('v3 trap-target {0} auth type'.format(trap)) + + if conf.exists('v3 trap-target {0} auth plaintext-key'.format(trap)): + # Set the authentication pass phrase used for authenticated SNMPv3 messages. + # cmdline option '-A' + trap_cfg['authPassword'] = conf.return_value('v3 trap-target {0} auth plaintext-key'.format(trap)) + + if conf.exists('v3 trap-target {0} auth encrypted-key'.format(trap)): + # Sets the keys to be used for SNMPv3 transactions. These options allow you to set the master authentication keys. + # cmdline option '-3m' + trap_cfg['authMasterKey'] = conf.return_value('v3 trap-target {0} auth encrypted-key'.format(trap)) + + if conf.exists('v3 trap-target {0} privacy type'.format(trap)): + # Set the privacy protocol (DES or AES) used for encrypted SNMPv3 messages. + # cmdline option '-x' + trap_cfg['privProtocol'] = conf.return_value('v3 trap-target {0} privacy type'.format(trap)) + + if conf.exists('v3 trap-target {0} privacy plaintext-key'.format(trap)): + # Set the privacy pass phrase used for encrypted SNMPv3 messages. + # cmdline option '-X' + trap_cfg['privPassword'] = conf.return_value('v3 trap-target {0} privacy plaintext-key'.format(trap)) + + if conf.exists('v3 trap-target {0} privacy encrypted-key'.format(trap)): + # Sets the keys to be used for SNMPv3 transactions. These options allow you to set the master encryption keys. + # cmdline option '-3M' + trap_cfg['privMasterKey'] = conf.return_value('v3 trap-target {0} privacy encrypted-key'.format(trap)) + + if conf.exists('v3 trap-target {0} protocol'.format(trap)): + trap_cfg['ipProto'] = conf.return_value('v3 trap-target {0} protocol'.format(trap)) + + if conf.exists('v3 trap-target {0} port'.format(trap)): + trap_cfg['ipPort'] = conf.return_value('v3 trap-target {0} port'.format(trap)) + + if conf.exists('v3 trap-target {0} type'.format(trap)): + trap_cfg['type'] = conf.return_value('v3 trap-target {0} type'.format(trap)) + + # Determine securityLevel used for SNMPv3 messages (noAuthNoPriv|authNoPriv|authPriv). + # Appropriate pass phrase(s) must provided when using any level higher than noAuthNoPriv. + if trap_cfg['authPassword'] or trap_cfg['authMasterKey']: + if trap_cfg['privProtocol'] or trap_cfg['privPassword']: + trap_cfg['secLevel'] = 'authPriv' + else: + trap_cfg['secLevel'] = 'authNoPriv' + + snmp['v3_traps'].append(trap_cfg) + + # + # 'set service snmp v3 tsm' + # + if conf.exists('v3 tsm'): + if conf.exists('v3 tsm local-key'): + snmp['v3_tsm_key'] = conf.return_value('v3 tsm local-key') + + if conf.exists('v3 tsm port'): + snmp['v3_tsm_port'] = conf.return_value('v3 tsm port') + + # + # 'set service snmp v3 user' + # + if conf.exists('v3 user'): + for user in conf.list_nodes('v3 user'): + user_cfg = { + 'name': user, + 'authMasterKey': '', + 'authPassword': '', + 'authProtocol': '', + 'authOID': 'none', + 'engineID': '', + 'group': '', + 'mode': 'ro', + 'privMasterKey': '', + 'privPassword': '', + 'privOID': '', + 'privTsmKey': '', + 'privProtocol': '' + } + + # + # v3 user {0} auth + # + if conf.exists('v3 user {0} auth encrypted-key'.format(user)): + user_cfg['authMasterKey'] = conf.return_value('v3 user {0} auth encrypted-key'.format(user)) + + if conf.exists('v3 user {0} auth plaintext-key'.format(user)): + user_cfg['authPassword'] = conf.return_value('v3 user {0} auth plaintext-key'.format(user)) + + if conf.exists('v3 user {0} auth type'.format(user)): + type = conf.return_value('v3 user {0} auth type'.format(user)) + user_cfg['authProtocol'] = type + user_cfg['authOID'] = OIDs[type] + + # + # v3 user {0} engineid + # + if conf.exists('v3 user {0} engineid'.format(user)): + user_cfg['engineID'] = conf.return_value('v3 user {0} engineid'.format(user)) + + # + # v3 user {0} group + # + if conf.exists('v3 user {0} group'.format(user)): + user_cfg['group'] = conf.return_value('v3 user {0} group'.format(user)) + + # + # v3 user {0} mode + # + if conf.exists('v3 user {0} mode'.format(user)): + user_cfg['mode'] = conf.return_value('v3 user {0} mode'.format(user)) + + # + # v3 user {0} privacy + # + if conf.exists('v3 user {0} privacy encrypted-key'.format(user)): + user_cfg['privMasterKey'] = conf.return_value('v3 user {0} privacy encrypted-key'.format(user)) + + if conf.exists('v3 user {0} privacy plaintext-key'.format(user)): + user_cfg['privPassword'] = conf.return_value('v3 user {0} privacy plaintext-key'.format(user)) + + if conf.exists('v3 user {0} privacy tsm-key'.format(user)): + user_cfg['privTsmKey'] = conf.return_value('v3 user {0} privacy tsm-key'.format(user)) + + if conf.exists('v3 user {0} privacy type'.format(user)): + type = conf.return_value('v3 user {0} privacy type'.format(user)) + user_cfg['privProtocol'] = type + user_cfg['privOID'] = OIDs[type] + + snmp['v3_users'].append(user_cfg) + + # + # 'set service snmp v3 view' + # + if conf.exists('v3 view'): + for view in conf.list_nodes('v3 view'): + view_cfg = { + 'name': view, + 'oids': [] + } + + if conf.exists('v3 view {0} oid'.format(view)): + for oid in conf.list_nodes('v3 view {0} oid'.format(view)): + oid_cfg = { + 'oid': oid + } + view_cfg['oids'].append(oid_cfg) + snmp['v3_views'].append(view_cfg) + + return snmp + +def verify(snmp): + if snmp is None: + return None + + # bail out early if SNMP v3 is not configured + if not snmp['v3_enabled']: + return None + + tsmKeyPattern = re.compile('^[0-9A-F]{2}(:[0-9A-F]{2}){19}$', re.IGNORECASE) + + if snmp['v3_tsm_key']: + if not tsmKeyPattern.match(snmp['v3_tsm_key']): + if not os.path.isfile('/etc/snmp/tls/certs/' + snmp['v3_tsm_key']): + if not os.path.isfile('/config/snmp/tls/certs/' + snmp['v3_tsm_key']): + raise ConfigError('TSM key must be fingerprint or filename in "/config/snmp/tls/certs/" folder') + + if 'v3_groups' in snmp.keys(): + for group in snmp['v3_groups']: + # + # A view must exist prior to mapping it into a group + # + if 'view' in group.keys(): + error = True + if 'v3_views' in snmp.keys(): + for view in snmp['v3_views']: + if view['name'] == group['view']: + error = False + if error: + raise ConfigError('You must create view "{0}" first'.format(group['view'])) + else: + raise ConfigError('"view" must be specified') + + if not 'mode' in group.keys(): + raise ConfigError('"mode" must be specified') + + if not 'seclevel' in group.keys(): + raise ConfigError('"seclevel" must be specified') + + + if 'v3_traps' in snmp.keys(): + for trap in snmp['v3_traps']: + if trap['authPassword'] and trap['authMasterKey']: + raise ConfigError('Must specify only one of encrypted-key/plaintext-key for trap auth') + + if trap['authPassword'] == '' and trap['authMasterKey'] == '': + raise ConfigError('Must specify encrypted-key or plaintext-key for trap auth') + + if trap['privPassword'] and trap['privMasterKey']: + raise ConfigError('Must specify only one of encrypted-key/plaintext-key for trap privacy') + + if trap['privPassword'] == '' and trap['privMasterKey'] == '': + raise ConfigError('Must specify encrypted-key or plaintext-key for trap privacy') + + if not 'type' in trap.keys(): + raise ConfigError('v3 trap: "type" must be specified') + + if not 'authPassword' and 'authMasterKey' in trap.keys(): + raise ConfigError('v3 trap: "auth" must be specified') + + if not 'authProtocol' in trap.keys(): + raise ConfigError('v3 trap: "protocol" must be specified') + + if not 'privPassword' and 'privMasterKey' in trap.keys(): + raise ConfigError('v3 trap: "user" must be specified') + + if 'type' in trap.keys(): + if trap['type'] == 'trap' and trap['engineID'] == '': + raise ConfigError('must specify engineid if type is "trap"') + else: + raise ConfigError('"type" must be specified') + + + if 'v3_users' in snmp.keys(): + for user in snmp['v3_users']: + # + # Group must exist prior to mapping it into a group + # seclevel will be extracted from group + # + error = True + if user['group']: + if 'v3_groups' in snmp.keys(): + for group in snmp['v3_groups']: + if group['name'] == user['group']: + seclevel = group['seclevel'] + error = False + + if error: + raise ConfigError('You must create group "{0}" first'.format(user['group'])) + + # Depending on the configured security level + # the user has to provide additional info + if seclevel is 'auth' or seclevel is 'priv': + if user['authPassword'] and user['authMasterKey']: + raise ConfigError('Can not mix "encrypted-key" and "plaintext-key" for user auth') + + if user['authPassword'] == '' and user['authMasterKey'] == '': + raise ConfigError('Must specify encrypted-key or plaintext-key for user auth') + + if user['authProtocol'] == '': + raise ConfigError('Must specify auth type') + + # seclevel 'priv' is more restrictive + if seclevel is 'priv': + if user['privPassword'] and user['privMasterKey']: + raise ConfigError('Can not mix "encrypted-key" and "plaintext-key" for user privacy') + + if user['privPassword'] == '' and user['privMasterKey'] == '': + raise ConfigError('Must specify encrypted-key or plaintext-key for user privacy') + + if user['privMasterKey'] and user['engineID'] == '': + raise ConfigError('Can not have "encrypted-key" without engineid') + + if user['authPassword'] == '' and user['authMasterKey'] == '' and user['privTsmKey'] == '': + raise ConfigError('Must specify auth or tsm-key for user auth') + + if user['privProtocol'] == '': + raise ConfigError('Must specify privacy type') + + if user['mode'] == '': + raise ConfigError('Must specify user mode ro/rw') + + if user['privTsmKey']: + if not tsmKeyPattern.match(snmp['v3_tsm_key']): + if not os.path.isfile('/etc/snmp/tls/certs/' + snmp['v3_tsm_key']): + if not os.path.isfile('/config/snmp/tls/certs/' + snmp['v3_tsm_key']): + raise ConfigError('User TSM key must be fingerprint or filename in "/config/snmp/tls/certs/" folder') + + if 'v3_views' in snmp.keys(): + for view in snmp['v3_views']: + if not view['oids']: + raise ConfigError('Must configure an oid') + + return None + +def generate(snmp): + # + # As we are manipulating the snmpd user database we have to stop it first! + # This is even save if service is going to be removed + os.system("sudo systemctl stop snmpd.service") + rmfile(config_file_client) + rmfile(config_file_daemon) + rmfile(config_file_access) + rmfile(config_file_user) + + if snmp is None: + return None + + # Write client config file + tmpl = jinja2.Template(client_config_tmpl, trim_blocks=True) + config_text = tmpl.render(snmp) + with open(config_file_client, 'w') as f: + f.write(config_text) + + # Write server config file + tmpl = jinja2.Template(daemon_config_tmpl, trim_blocks=True) + config_text = tmpl.render(snmp) + with open(config_file_daemon, 'w') as f: + f.write(config_text) + + # Write access rights config file + tmpl = jinja2.Template(access_config_tmpl, trim_blocks=True) + config_text = tmpl.render(snmp) + with open(config_file_access, 'w') as f: + f.write(config_text) + + # Write access rights config file + tmpl = jinja2.Template(user_config_tmpl, trim_blocks=True) + config_text = tmpl.render(snmp) + with open(config_file_user, 'w') as f: + f.write(config_text) + + return None + +def apply(snmp): + if snmp is not None: + + nonvolatiledir = '/config/snmp/tls' + volatiledir = '/etc/snmp/tls' + if not os.path.exists(nonvolatiledir): + os.makedirs(nonvolatiledir) + os.chmod(nonvolatiledir, stat.S_IWUSR | stat.S_IRUSR) + # get uid for user 'snmp' + snmp_uid = pwd.getpwnam('snmp').pw_uid + os.chown(nonvolatiledir, snmp_uid, -1) + + # move SNMP certificate files from volatile location to non volatile /config/snmp + if os.path.exists(volatiledir) and os.path.isdir(volatiledir): + files = os.listdir(volatiledir) + for f in files: + shutil.move(volatiledir + '/' + f, nonvolatiledir) + os.chmod(nonvolatiledir + '/' + f, stat.S_IWUSR | stat.S_IRUSR) + + os.rmdir(volatiledir) + os.symlink(nonvolatiledir, volatiledir) + + if os.path.islink(volatiledir): + link = os.readlink(volatiledir) + if link != nonvolatiledir: + os.unlink(volatiledir) + os.symlink(nonvolatiledir, volatiledir) + + # start SNMP daemon + os.system("sudo systemctl restart snmpd.service") + + # the passwords are not available immediately so this is a workaround + # and should be changed to polling + time.sleep(2) + + # Back in the Perl days the configuration was re-read and any + # plaintext password inside the configuration was replaced by + # the encrypted one which can be found in 'config_file_user' + with open(config_file_user, 'r') as f: + engineID = '' + for line in f: + if line.startswith('oldEngineID'): + string = line.split(' ') + engineID = string[1] + + if line.startswith('usmUser'): + string = line.split(' ') + cfg = { + 'user': string[4].replace(r'"', ''), + 'auth_pw': string[8], + 'priv_pw': string[10] + } + # No need to take care about the VyOS internal user + if cfg['user'] == snmp['vyos_user']: + continue + + # Now update the running configuration + # + # Currently when executing os.system() the environment does not have the vyos_libexec_dir variable set, see T685 + os.system('vyos_libexec_dir=/usr/libexec/vyos /opt/vyatta/sbin/my_set service snmp v3 user "{0}" engineid {1} > /dev/null'.format(cfg['user'], engineID)) + os.system('vyos_libexec_dir=/usr/libexec/vyos /opt/vyatta/sbin/my_set service snmp v3 user "{0}" auth encrypted-key {1} > /dev/null'.format(cfg['user'], cfg['auth_pw'])) + os.system('vyos_libexec_dir=/usr/libexec/vyos /opt/vyatta/sbin/my_set service snmp v3 user "{0}" privacy encrypted-key {1} > /dev/null'.format(cfg['user'], cfg['priv_pw'])) + os.system('vyos_libexec_dir=/usr/libexec/vyos /opt/vyatta/sbin/my_delete service snmp v3 user "{0}" auth plaintext-key > /dev/null'.format(cfg['user'])) + os.system('vyos_libexec_dir=/usr/libexec/vyos /opt/vyatta/sbin/my_delete service snmp v3 user "{0}" privacy plaintext-key > /dev/null'.format(cfg['user'])) + + return None + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/ssh.py b/src/conf_mode/ssh.py new file mode 100755 index 0000000..f1ac194 --- /dev/null +++ b/src/conf_mode/ssh.py @@ -0,0 +1,255 @@ +#!/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/>. +# +# + +import sys +import os + +import jinja2 + +from vyos.config import Config +from vyos import ConfigError + +config_file = r'/etc/ssh/sshd_config' + +# Please be careful if you edit the template. +config_tmpl = """ + +### Autogenerated by ssh.py ### + +# Non-configurable defaults +Protocol 2 +HostKey /etc/ssh/ssh_host_rsa_key +HostKey /etc/ssh/ssh_host_dsa_key +HostKey /etc/ssh/ssh_host_ecdsa_key +HostKey /etc/ssh/ssh_host_ed25519_key +UsePrivilegeSeparation yes +KeyRegenerationInterval 3600 +ServerKeyBits 1024 +SyslogFacility AUTH +LoginGraceTime 120 +StrictModes yes +RSAAuthentication yes +PubkeyAuthentication yes +IgnoreRhosts yes +RhostsRSAAuthentication no +HostbasedAuthentication no +PermitEmptyPasswords no +ChallengeResponseAuthentication no +X11Forwarding yes +X11DisplayOffset 10 +PrintMotd no +PrintLastLog yes +TCPKeepAlive yes +Banner /etc/issue.net +Subsystem sftp /usr/lib/openssh/sftp-server +UsePAM yes +HostKey /etc/ssh/ssh_host_key + +# Specifies whether sshd should look up the remote host name, +# and to check that the resolved host name for the remote IP +# address maps back to the very same IP address. +UseDNS {{ host_validation }} + +# Specifies the port number that sshd listens on. The default is 22. +# Multiple options of this type are permitted. +Port {{ port }} + +# Gives the verbosity level that is used when logging messages from sshd +LogLevel {{ log_level }} + +# Specifies whether root can log in using ssh +PermitRootLogin {{ allow_root }} + +# Specifies whether password authentication is allowed +PasswordAuthentication {{ password_authentication }} + +{% if listen_on -%} +# Specifies the local addresses sshd should listen on +{% for a in listen_on -%} +ListenAddress {{ a }} +{% endfor -%} +{% endif %} + +{% if ciphers -%} +# Specifies the ciphers allowed. Multiple ciphers must be comma-separated. +# +# NOTE: As of now, there is no 'multi' node for 'ciphers', thus we have only one :/ +Ciphers {{ ciphers | join(",") }} +{% endif %} + +{% if mac -%} +# Specifies the available MAC (message authentication code) algorithms. The MAC +# algorithm is used for data integrity protection. Multiple algorithms must be +# comma-separated. +# +# NOTE: As of now, there is no 'multi' node for 'mac', thus we have only one :/ +MACs {{ mac | join(",") }} +{% endif %} + +{% if key_exchange -%} +# Specifies the available KEX (Key Exchange) algorithms. Multiple algorithms must +# be comma-separated. +# +# NOTE: As of now, there is no 'multi' node for 'key-exchange', thus we have only one :/ +KexAlgorithms {{ key_exchange | join(",") }} +{% endif %} + +{% if allow_users -%} +# This keyword can be followed by a list of user name patterns, separated by spaces. +# If specified, login is allowed only for user names that match one of the patterns. +# Only user names are valid, a numerical user ID is not recognized. +AllowUsers {{ allow_users | join(" ") }} +{% endif %} + +{% if allow_groups -%} +# This keyword can be followed by a list of group name patterns, separated by spaces. +# If specified, login is allowed only for users whose primary group or supplementary +# group list matches one of the patterns. Only group names are valid, a numerical group +# ID is not recognized. +AllowGroups {{ allow_groups | join(" ") }} +{% endif %} + +{% if deny_users -%} +# This keyword can be followed by a list of user name patterns, separated by spaces. +# Login is disallowed for user names that match one of the patterns. Only user names +# are valid, a numerical user ID is not recognized. +DenyUsers {{ deny_users | join(" ") }} +{% endif %} + +{% if deny_groups -%} +# This keyword can be followed by a list of group name patterns, separated by spaces. +# Login is disallowed for users whose primary group or supplementary group list matches +# one of the patterns. Only group names are valid, a numerical group ID is not recognized. +DenyGroups {{ deny_groups | join(" ") }} +{% endif %} +""" + +default_config_data = { + 'port' : '22', + 'log_level': 'INFO', + 'allow_root': 'no', + 'password_authentication': 'yes', + 'host_validation': 'yes' +} + +def get_config(): + ssh = default_config_data + conf = Config() + if not conf.exists('service ssh'): + return None + else: + conf.set_level('service ssh') + + if conf.exists('access-control allow user'): + allow_users = conf.return_values('access-control allow user') + ssh['allow_users'] = allow_users + + if conf.exists('access-control allow group'): + allow_groups = conf.return_values('access-control allow group') + ssh['allow_groups'] = allow_groups + + if conf.exists('access-control deny user'): + deny_users = conf.return_values('access-control deny user') + ssh['deny_users'] = deny_users + + if conf.exists('access-control deny group'): + deny_groups = conf.return_values('access-control deny group') + ssh['deny_groups'] = deny_groups + + if conf.exists('allow-root'): + ssh['allow-root'] = 'yes' + + if conf.exists('ciphers'): + ciphers = conf.return_values('ciphers') + ssh['ciphers'] = ciphers + + if conf.exists('disable-host-validation'): + ssh['host_validation'] = 'no' + + if conf.exists('disable-password-authentication'): + ssh['password_authentication'] = 'no' + + if conf.exists('key-exchange'): + kex = conf.return_values('key-exchange') + ssh['key_exchange'] = kex + + if conf.exists('listen-address'): + # We can listen on both IPv4 and IPv6 addresses + # Maybe there could be a check in the future if the configured IP address + # is configured on this system at all? + addresses = conf.return_values('listen-address') + listen = [] + + for addr in addresses: + listen.append(addr) + + ssh['listen_on'] = listen + + if conf.exists('loglevel'): + ssh['log_level'] = conf.return_value('loglevel') + + if conf.exists('mac'): + mac = conf.return_values('mac') + ssh['mac'] = mac + + if conf.exists('port'): + port = conf.return_value('port') + ssh['port'] = port + + return ssh + +def verify(ssh): + if ssh is None: + return None + + if 'loglevel' in ssh.keys(): + allowed_loglevel = 'QUIET, FATAL, ERROR, INFO, VERBOSE' + if not ssh['loglevel'] in allowed_loglevel: + raise ConfigError('loglevel must be one of "{0}"\n'.format(allowed_loglevel)) + + return None + +def generate(ssh): + if ssh is None: + return None + + tmpl = jinja2.Template(config_tmpl) + config_text = tmpl.render(ssh) + with open(config_file, 'w') as f: + f.write(config_text) + return None + +def apply(ssh): + if ssh is not None and 'port' in ssh.keys(): + os.system("sudo systemctl restart ssh") + else: + # SSH access is removed in the commit + os.system("sudo systemctl stop ssh") + os.unlink(config_file) + + return None + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/conf_mode/task_scheduler.py b/src/conf_mode/task_scheduler.py new file mode 100755 index 0000000..285afe2 --- /dev/null +++ b/src/conf_mode/task_scheduler.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2017 VyOS maintainers and contributors +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 or later as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +# + +import os +import re +import sys + +from vyos.config import Config +from vyos import ConfigError + + +crontab_file = "/etc/cron.d/vyos-crontab" + + +def format_task(minute="*", hour="*", day="*", dayofweek="*", month="*", user="root", rawspec=None, command=""): + fmt_full = "{minute} {hour} {day} {month} {dayofweek} {user} {command}\n" + fmt_raw = "{spec} {user} {command}\n" + + if rawspec is None: + s = fmt_full.format(minute=minute, hour=hour, day=day, + dayofweek=dayofweek, month=month, command=command, user=user) + else: + s = fmt_raw.format(spec=rawspec, user=user, command=command) + + return s + +def split_interval(s): + result = re.search(r"(\d+)([mdh]?)", s) + value = int(result.group(1)) + suffix = result.group(2) + return( (value, suffix) ) + +def make_command(executable, arguments): + if arguments: + return("sg vyattacfg \"{0} {1}\"".format(executable, arguments)) + else: + return(executable) + +def get_config(): + conf = Config() + conf.set_level("system task-scheduler task") + task_names = conf.list_nodes("") + tasks = [] + + for name in task_names: + interval = conf.return_value("{0} interval".format(name)) + spec = conf.return_value("{0} crontab-spec".format(name)) + executable = conf.return_value("{0} executable path".format(name)) + args = conf.return_value("{0} executable arguments".format(name)) + task = { + "name": name, + "interval": interval, + "spec": spec, + "executable": executable, + "args": args + } + tasks.append(task) + + return tasks + +def verify(tasks): + for task in tasks: + if not task["interval"] and not task["spec"]: + raise ConfigError("Invalid task {0}: must define either interval or crontab-spec".format(task["name"])) + + if task["interval"]: + if task["spec"]: + raise ConfigError("Invalid task {0}: cannot use interval and crontab-spec at the same time".format(task["name"])) + + if not re.match(r"^\d+[mdh]?$", task["interval"]): + raise(ConfigError("Invalid interval {0} in task {1}: interval should be a number optionally followed by m, h, or d".format(task["name"], task["interval"]))) + else: + # Check if values are within allowed range + value, suffix = split_interval(task["interval"]) + + if not suffix or suffix == "m": + if value > 60: + raise ConfigError("Invalid task {0}: interval in minutes must not exceed 60".format(task["name"])) + elif suffix == "h": + if value > 24: + raise ConfigError("Invalid task {0}: interval in hours must not exceed 24".format(task["name"])) + elif suffix == "d": + if value > 31: + raise ConfigError("Invalid task {0}: interval in days must not exceed 31".format(task["name"])) + + if not task["executable"]: + raise ConfigError("Invalid task {0}: executable is not defined".format(task["name"])) + else: + # Check if executable exists and is executable + if not (os.path.isfile(task["executable"]) and os.access(task["executable"], os.X_OK)): + raise ConfigError("Invalid task {0}: file {1} does not exist or is not executable".format(task["name"], task["executable"])) + +def generate(tasks): + crontab_header = "### Generated by vyos-update-crontab.py ###\n" + if len(tasks) == 0: + if os.path.exists(crontab_file): + os.remove(crontab_file) + else: + pass + else: + crontab_lines = [] + for task in tasks: + command = make_command(task["executable"], task["args"]) + if task["spec"]: + line = format_task(command=command, rawspec=task["spec"]) + else: + value, suffix = split_interval(task["interval"]) + if not suffix or suffix == "m": + line = format_task(command=command, minute="*/{0}".format(value)) + elif suffix == "h": + line = format_task(command=command, minute="0", hour="*/{0}".format(value)) + elif suffix == "d": + line = format_task(command=command, minute="0", hour="0", day="*/{0}".format(value)) + crontab_lines.append(line) + + with open(crontab_file, 'w') as f: + f.write(crontab_header) + f.writelines(crontab_lines) + +def apply(config): + # No daemon restarts etc. needed for cron + pass + + +if __name__ == '__main__': + try: + c = get_config() + verify(c) + generate(c) + apply(c) + except ConfigError as e: + print(e) + sys.exit(1) diff --git a/src/helpers/commands-pipe.py b/src/helpers/commands-pipe.py new file mode 100755 index 0000000..1120bb0 --- /dev/null +++ b/src/helpers/commands-pipe.py @@ -0,0 +1,29 @@ +#!/usr/bin/python3 + +import sys +import re + +from signal import signal, SIGPIPE, SIG_DFL +from vyos.configtree import ConfigTree + +signal(SIGPIPE,SIG_DFL) + +config_string = sys.stdin.read().strip() + +if not config_string: + sys.exit(0) + +# When used in conf mode pipe, the config given to the script is likely incomplete +# and breaks the "all top level nodes are neither tag nor leaf" +# invariant, so we wrap it into a fake node. +# Since nodes don't normally start with an underscore, +# __root__ is hygienic enough. +config_string = "__root__ {{ {0} \n }}".format(config_string) + +config_re = re.compile(r'(set|comment)\s+__root__\s+(.*)') + +config = ConfigTree(config_string) +commands = config.to_commands() +commands = config_re.sub("\\1 \\2", commands) + +print(commands) diff --git a/src/helpers/validate-value.py b/src/helpers/validate-value.py new file mode 100755 index 0000000..d702739 --- /dev/null +++ b/src/helpers/validate-value.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 + +import re +import os +import sys +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument('--regex', action='append') +parser.add_argument('--exec', action='append') +parser.add_argument('--value', action='store') + +args = parser.parse_args() + +debug = False + +# Multiple arguments work like logical OR + +try: + for r in args.regex: + if re.fullmatch(r, args.value): + sys.exit(0) +except Exception as exn: + if debug: + print(exn) + else: + pass + +try: + for cmd in args.exec: + cmd = "{0} {1}".format(cmd, args.value) + if debug: + print(cmd) + res = os.system(cmd) + if res == 0: + sys.exit(0) +except Exception as exn: + if debug: + print(exn) + else: + pass + +sys.exit(1) diff --git a/src/migration-scripts/config-management/0-to-1 b/src/migration-scripts/config-management/0-to-1 new file mode 100755 index 0000000..3443591 --- /dev/null +++ b/src/migration-scripts/config-management/0-to-1 @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +# Add commit-revisions option if it doesn't exist + +import sys + +from vyos.configtree import ConfigTree + +if (len(sys.argv) < 1): + print("Must specify file name!") + sys.exit(1) + +file_name = sys.argv[1] + +with open(file_name, 'r') as f: + config_file = f.read() + +config = ConfigTree(config_file) + +if config.exists(['system', 'config-management', 'commit-revisions']): + # Nothing to do + sys.exit(0) +else: + config.set(['system', 'config-management', 'commit-revisions'], value='200') + + 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)) + sys.exit(1) diff --git a/src/migration-scripts/system/7-to-8 b/src/migration-scripts/system/7-to-8 new file mode 100755 index 0000000..4cbb21f --- /dev/null +++ b/src/migration-scripts/system/7-to-8 @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 + +# Converts "system gateway-address" option to "protocols static route 0.0.0.0/0 next-hop $gw" + +import sys + +from vyos.configtree import ConfigTree + +if (len(sys.argv) < 1): + print("Must specify file name!") + sys.exit(1) + +file_name = sys.argv[1] + +with open(file_name, 'r') as f: + config_file = f.read() + +config = ConfigTree(config_file) + +if not config.exists(['system', 'gateway-address']): + # Nothing to do + sys.exit(0) +else: + # Save the address + gw = config.return_value(['system', 'gateway-address']) + + # Create the node for the new syntax + # Note: next-hop is a tag node, gateway address is its child, not a value + config.set(['protocols', 'static', 'route', '0.0.0.0/0', 'next-hop', gw]) + + # Delete the node with the old syntax + config.delete(['system', 'gateway-address']) + + # Now, the interesting part. Both route and next-hop are supposed to be tag nodes, + # which you can verify with "cli-shell-api isTag $configPath". + # They must be formatted as such to load correctly. + config.set_tag(['protocols', 'static', 'route']) + config.set_tag(['protocols', 'static', 'route', '0.0.0.0/0', 'next-hop']) + + 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)) + sys.exit(1) diff --git a/src/op_mode/cpu_summary.py b/src/op_mode/cpu_summary.py new file mode 100755 index 0000000..7324c75 --- /dev/null +++ b/src/op_mode/cpu_summary.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 + +import re + +from vyos.util import colon_separated_to_dict + + +FILE_NAME = '/proc/cpuinfo' + +with open(FILE_NAME, 'r') as f: + data_raw = f.read() + +data = colon_separated_to_dict(data_raw) + +# Accumulate all data in a dict for future support for machine-readable output +cpu_data = {} +cpu_data['cpu_number'] = len(data['processor']) +cpu_data['models'] = list(set(data['model name'])) + +# Strip extra whitespace from CPU model names, /proc/cpuinfo is prone to that +cpu_data['models'] = map(lambda s: re.sub(r'\s+', ' ', s), cpu_data['models']) + +print("CPU(s): {0}".format(cpu_data['cpu_number'])) +print("CPU model(s): {0}".format(",".join(cpu_data['models']))) diff --git a/src/op_mode/dns_forwarding_reset.py b/src/op_mode/dns_forwarding_reset.py new file mode 100755 index 0000000..da4fba3 --- /dev/null +++ b/src/op_mode/dns_forwarding_reset.py @@ -0,0 +1,49 @@ +#!/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 sys +import argparse + +import vyos.config + +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 = vyos.config.Config() + if not c.exists_effective('service dns forwarding'): + print("DNS forwarding is not configured") + sys.exit(0) + + if args.all: + os.system("rec_control wipe-cache \'.$\'") + sys.exit(1) + elif args.domain: + os.system("rec_control wipe-cache \'{0}$\'".format(args.domain)) + else: + parser.print_help() + sys.exit(1) diff --git a/src/op_mode/dns_forwarding_restart.sh b/src/op_mode/dns_forwarding_restart.sh new file mode 100755 index 0000000..12106fc --- /dev/null +++ b/src/op_mode/dns_forwarding_restart.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +if cli-shell-api exists service dns forwarding; then + echo "Restarting the DNS forwarding service" + systemctl restart pdns-recursor +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 new file mode 100755 index 0000000..f626244 --- /dev/null +++ b/src/op_mode/dns_forwarding_statistics.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 + +import subprocess +import jinja2 +import sys + +from vyos.config import Config + +PDNS_CMD='/usr/bin/rec_control' + +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") + sys.exit(0) + + data = {} + + data['cache_entries'] = subprocess.check_output([PDNS_CMD, 'get cache-entries']).decode() + data['cache_size'] = "{0:.2f}".format( int(subprocess.check_output([PDNS_CMD, 'get cache-bytes']).decode()) / 1024 ) + + tmpl = jinja2.Template(OUT_TMPL_SRC) + print(tmpl.render(data)) diff --git a/src/op_mode/maya_date.py b/src/op_mode/maya_date.py new file mode 100755 index 0000000..7d8aefc --- /dev/null +++ b/src/op_mode/maya_date.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2013, 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/>. + +import sys + +class MayaDate(object): + """ Converts number of days since UNIX epoch + to the Maya calendar date. + + Ancient Maya people used three independent calendars for + different purposes. + + The long count calendar is for recording historical events. + It represents the number of days passed + since some date in the past the Maya believed is the day + our world was created. + + Tzolkin calendar is for religious purposes, it has + two independent cycles of 13 and 20 days, where 13 day + cycle days are numbered, and 20 day cycle days are named. + + Haab calendar is for agriculture and daily life, it's a + 365 day calendar with 18 months 20 days each, and 5 + nameless days. + + The smallest unit of the long count calendar is one day (kin). + + """ + + """ The long count calendar uses five different base 18 or base 20 + cycles. Modern scholars write long count calendar dates in a dot separated format + from longest to shortest cycle, + <baktun>.<katun>.<tun>.<winal>.<kin> + for example, "13.0.0.9.2". + + Classic version actually used by the ancient Maya wraps around + every 13th baktun, but modern historians often use longer cycles + such as piktun = 20 baktun. + + """ + kin = 1 + winal = 20 # 20 kin + tun = 360 # 18 winal + katun = 7200 # 20 tun + baktun = 144000 # 20 katun + + """ Tzolk'in date is composed of two independent cycles. + Dates repeat every 260 days, 13 Ajaw is considered the end + of tzolk'in. + + Every day of the 20 day cycle has unique name, we number + them from zero so it's easier to map the remainder to day: + """ + tzolkin_days = { 0: "Imix'", + 1: "Ik'", + 2: "Ak'b'al", + 3: "K'an", + 4: "Chikchan", + 5: "Kimi", + 6: "Manik'", + 7: "Lamat", + 8: "Muluk", + 9: "Ok", + 10: "Chuwen", + 11: "Eb'", + 12: "B'en", + 13: "Ix", + 14: "Men", + 15: "Kib'", + 16: "Kab'an", + 17: "Etz'nab'", + 18: "Kawak", + 19: "Ajaw" } + + """ As said above, haab (year) has 19 months. Only 18 are + true months of 20 days each, the remaining 5 days called "wayeb" + do not really belong to any month, but we think of them as a pseudo-month + for convenience. + + Also, note that days of the month are actually numbered from 0, not from 1, + it's not for technical reasons. + """ + haab_months = { 0: "Pop", + 1: "Wo'", + 2: "Sip", + 3: "Sotz'", + 4: "Sek", + 5: "Xul", + 6: "Yaxk'in'", + 7: "Mol", + 8: "Ch'en", + 9: "Yax", + 10: "Sak'", + 11: "Keh", + 12: "Mak", + 13: "K'ank'in", + 14: "Muwan'", + 15: "Pax", + 16: "K'ayab", + 17: "Kumk'u", + 18: "Wayeb'" } + + """ Now we need to map the beginning of UNIX epoch + (Jan 1 1970 00:00 UTC) to the beginning of the long count + calendar (0.0.0.0.0, 4 Ajaw, 8 Kumk'u). + + The problem with mapping the long count calendar to + any other is that its start date is not known exactly. + + The most widely accepted hypothesis suggests it was + August 11, 3114 BC gregorian date. In this case UNIX epoch + starts on 12.17.16.7.5, 13 Chikchan, 3 K'ank'in + + It's known as Goodman-Martinez-Thompson (GMT) correlation + constant. + """ + start_days = 1856305 + + """ Seconds in day, for conversion from timestamp """ + seconds_in_day = 60 * 60 * 24 + + def __init__(self, timestamp): + if timestamp is None: + self.days = self.start_days + else: + self.days = self.start_days + (int(timestamp) // self.seconds_in_day) + + def long_count_date(self): + """ Returns long count date string """ + days = self.days + + cur_baktun = days // self.baktun + days = days % self.baktun + + cur_katun = days // self.katun + days = days % self.katun + + cur_tun = days // self.tun + days = days % self.tun + + cur_winal = days // self.winal + days = days % self.winal + + cur_kin = days + + longcount_string = "{0}.{1}.{2}.{3}.{4}".format( cur_baktun, + cur_katun, + cur_tun, + cur_winal, + cur_kin ) + return(longcount_string) + + def tzolkin_date(self): + """ Returns tzolkin date string """ + days = self.days + + """ The start date is not the beginning of both cycles, + it's 4 Ajaw. So we need to add 4 to the 13 days cycle day, + and substract 1 from the 20 day cycle to get correct result. + """ + tzolkin_13 = (days + 4) % 13 + tzolkin_20 = (days - 1) % 20 + + tzolkin_string = "{0} {1}".format(tzolkin_13, self.tzolkin_days[tzolkin_20]) + + return(tzolkin_string) + + def haab_date(self): + """ Returns haab date string. + + The time start on 8 Kumk'u rather than 0 Pop, which is + 17 days before the new haab, so we need to substract 17 + from the current date to get correct result. + """ + days = self.days + + haab_day = (days - 17) % 365 + haab_month = haab_day // 20 + haab_day_of_month = haab_day % 20 + + haab_string = "{0} {1}".format(haab_day_of_month, self.haab_months[haab_month]) + + return(haab_string) + + def date(self): + return("{0}, {1}, {2}".format( self.long_count_date(), self.tzolkin_date(), self.haab_date() )) + +if __name__ == '__main__': + try: + timestamp = sys.argv[1] + except: + print("Please specify timestamp in the argument") + sys.exit(1) + + maya_date = MayaDate(timestamp) + print(maya_date.date()) diff --git a/src/op_mode/show-configuration-files.sh b/src/op_mode/show-configuration-files.sh new file mode 100755 index 0000000..ad8e074 --- /dev/null +++ b/src/op_mode/show-configuration-files.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# Wrapper script for the show configuration files command +find ${vyatta_sysconfdir}/config/ \ + -type f \ + -not -name ".*" \ + -not -name "config.boot.*" \ + -printf "%f\t(%Tc)\t%T@\n" \ + | sort -r -k3 \ + | awk -F"\t" '{printf ("%-20s\t%s\n", $1,$2) ;}' diff --git a/src/op_mode/show-disk-format.sh b/src/op_mode/show-disk-format.sh new file mode 100755 index 0000000..61b15a5 --- /dev/null +++ b/src/op_mode/show-disk-format.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +disk_dev="/dev/$1" +if [ ! -b "$disk_dev" ];then + echo "$3 is not a disk device" + exit 1 +fi +sudo /sbin/fdisk -l "$disk_dev" diff --git a/src/op_mode/show-raid.sh b/src/op_mode/show-raid.sh new file mode 100755 index 0000000..ba41746 --- /dev/null +++ b/src/op_mode/show-raid.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +raid_set_name=$1 +raid_sets=`cat /proc/partitions | grep md | awk '{ print $4 }'` +valid_set=`echo $raid_sets | grep $raid_set_name` +if [ -z $valid_set ]; then + echo "$raid_set_name is not a RAID set" +else + if [ -r /dev/${raid_set_name} ]; then + # This should work without sudo because we have read + # access to the dev, but for some reason mdadm must be + # run as root in order to succeed. + sudo /sbin/mdadm --detail /dev/${raid_set_name} + else + echo "Must be administrator or root to display RAID status" + fi +fi diff --git a/src/op_mode/snmp.py b/src/op_mode/snmp.py new file mode 100755 index 0000000..e08441f --- /dev/null +++ b/src/op_mode/snmp.py @@ -0,0 +1,77 @@ +#!/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: snmp.py +# Purpose: +# Show SNMP community/remote hosts +# Used by the "run show snmp community" commands. + +import os +import sys +import argparse + +from vyos.config import Config + +config_file_daemon = r'/etc/snmp/snmpd.conf' + +parser = argparse.ArgumentParser(description='Retrieve infomration from running SNMP daemon') +parser.add_argument('--allowed', action="store_true", help='Show available SNMP communities') +parser.add_argument('--community', action="store", help='Show status of given SNMP community', type=str) +parser.add_argument('--host', action="store", help='SNMP host to connect to', type=str, default='localhost') + +config = { + 'communities': [], +} + +def read_config(): + with open(config_file_daemon, 'r') as f: + for line in f: + # Only get configured SNMP communitie + if line.startswith('rocommunity') or line.startswith('rwcommunity'): + string = line.split(' ') + # append community to the output list only once + c = string[1] + if c not in config['communities']: + config['communities'].append(c) + +def show_all(): + if len(config['communities']) > 0: + print(' '.join(config['communities'])) + +def show_community(c, h): + print('Status of SNMP community {0} on {1}'.format(c, h), flush=True) + os.system('/usr/bin/snmpstatus -t1 -v1 -c {0} {1}'.format(c, h)) + +if __name__ == '__main__': + args = parser.parse_args() + + # Do nothing if service is not configured + c = Config() + if not c.exists_effective('service snmp'): + print("SNMP service is not configured") + sys.exit(0) + + read_config() + + if args.allowed: + show_all() + sys.exit(1) + elif args.community: + show_community(args.community, args.host) + sys.exit(1) + else: + parser.print_help() + sys.exit(1) diff --git a/src/op_mode/snmp_ifmib.py b/src/op_mode/snmp_ifmib.py new file mode 100755 index 0000000..9d56a95 --- /dev/null +++ b/src/op_mode/snmp_ifmib.py @@ -0,0 +1,128 @@ +#!/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: snmp_ifmib.py +# Purpose: +# Show SNMP MIB information +# Used by the "run show snmp mib" commands. + +import sys +import argparse +import netifaces +import subprocess + +from vyos.config import Config + +parser = argparse.ArgumentParser(description='Retrieve SNMP interfaces information') +parser.add_argument('--ifindex', action='store', nargs='?', const='all', help='Show interface index') +parser.add_argument('--ifalias', action='store', nargs='?', const='all', help='Show interface aliase') +parser.add_argument('--ifdescr', action='store', nargs='?', const='all', help='Show interface description') + +def show_ifindex(i): + proc = subprocess.Popen(['/bin/ip', 'link', 'show', i], stdout=subprocess.PIPE) + (out, err) = proc.communicate() + # convert output to string + string = out.decode("utf-8") + + index = 'ifIndex = ' + string.split(':')[0] + return index.replace('\n', '') + +def show_ifalias(i): + proc = subprocess.Popen(['/bin/ip', 'link', 'show', i], stdout=subprocess.PIPE) + (out, err) = proc.communicate() + # convert output to string + string = out.decode("utf-8") + + if 'alias' in string: + alias = 'ifAlias = ' + string.split('alias')[1].lstrip() + else: + alias = 'ifAlias = ' + i + + return alias.replace('\n', '') + +def show_ifdescr(i): + ven_id = '' + dev_id = '' + + try: + with open(r'/sys/class/net/' + i + '/device/vendor', 'r') as f: + ven_id = f.read().replace('\n', '') + except FileNotFoundError: + pass + + try: + with open(r'/sys/class/net/' + i + '/device/device', 'r') as f: + dev_id = f.read().replace('\n', '') + except FileNotFoundError: + pass + + if ven_id == '' and dev_id == '': + ret = 'ifDescr = {0}'.format(i) + return ret + + device = str(ven_id) + ':' + str(dev_id) + proc = subprocess.Popen(['/usr/bin/lspci', '-mm', '-d', device], stdout=subprocess.PIPE) + (out, err) = proc.communicate() + + # convert output to string + string = out.decode("utf-8").split('"') + vendor = string[3] + device = string[5] + + ret = 'ifDescr = {0} {1}'.format(vendor, device) + return ret.replace('\n', '') + +if __name__ == '__main__': + args = parser.parse_args() + + # Do nothing if service is not configured + c = Config() + if not c.exists_effective('service snmp'): + print("SNMP service is not configured") + sys.exit(0) + + if args.ifindex: + if args.ifindex == 'all': + for i in netifaces.interfaces(): + print('{0}: {1}'.format(i, show_ifindex(i))) + else: + print('{0}: {1}'.format(args.ifindex, show_ifindex(args.ifindex))) + + elif args.ifalias: + if args.ifalias == 'all': + for i in netifaces.interfaces(): + print('{0}: {1}'.format(i, show_ifalias(i))) + else: + print('{0}: {1}'.format(args.ifalias, show_ifalias(args.ifalias))) + + elif args.ifdescr: + if args.ifdescr == 'all': + for i in netifaces.interfaces(): + print('{0}: {1}'.format(i, show_ifdescr(i))) + else: + print('{0}: {1}'.format(args.ifdescr, show_ifdescr(args.ifdescr))) + + else: + #eth0: ifIndex = 2 + # ifAlias = NET-MYBLL-MUCI-BACKBONE + # ifDescr = VMware VMXNET3 Ethernet Controller + #lo: ifIndex = 1 + for i in netifaces.interfaces(): + print('{0}:\t{1}'.format(i, show_ifindex(i))) + print('\t{0}'.format(show_ifalias(i))) + print('\t{0}'.format(show_ifdescr(i))) + + sys.exit(1) diff --git a/src/op_mode/snmp_v3.py b/src/op_mode/snmp_v3.py new file mode 100755 index 0000000..92601f1 --- /dev/null +++ b/src/op_mode/snmp_v3.py @@ -0,0 +1,180 @@ +#!/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: snmp_v3.py +# Purpose: +# Show SNMP v3 information +# Used by the "run show snmp v3" commands. + +import sys +import jinja2 +import argparse + +from vyos.config import Config + +parser = argparse.ArgumentParser(description='Retrieve SNMP v3 information') +parser.add_argument('--all', action="store_true", help='Show all available information') +parser.add_argument('--group', action="store_true", help='Show the list of configured groups') +parser.add_argument('--trap', action="store_true", help='Show the list of configured targets') +parser.add_argument('--user', action="store_true", help='Show the list of configured users') +parser.add_argument('--view', action="store_true", help='Show the list of configured views') + +GROUP_OUTP_TMPL_SRC = """ +SNMPv3 Groups: + + Group View + ----- ---- + {% if group -%}{% for g in group -%} + {{ "%-20s" | format(g.name) }}{{ g.view }}({{ g.mode }}) + {% endfor %}{% endif %} +""" + +TRAPTGT_OUTP_TMPL_SRC = """ +SNMPv3 Trap-targets: + + Tpap-target Port Protocol Auth Priv Type EngineID User + ----------- ---- -------- ---- ---- ---- -------- ---- + {% if trap -%}{% for t in trap -%} + {{ "%-20s" | format(t.name) }} {{ t.port }} {{ t.proto }} {{ t.auth }} {{ t.priv }} {{ t.type }} {{ "%-32s" | format(t.engID) }} {{ t.user }} + {% endfor %}{% endif %} +""" + +USER_OUTP_TMPL_SRC = """ +SNMPv3 Users: + + User Auth Priv Mode Group + ---- ---- ---- ---- ----- + {% if user -%}{% for u in user -%} + {{ "%-20s" | format(u.name) }}{{ u.auth }} {{ u.priv }} {{ u.mode }} {{ u.group }} + {% endfor %}{% endif %} +""" + +VIEW_OUTP_TMPL_SRC = """ +SNMPv3 Views: + {% if view -%}{% for v in view %} + View : {{ v.name }} + OIDs : .{{ v.oids | join("\n .")}} + {% endfor %}{% endif %} +""" + +if __name__ == '__main__': + args = parser.parse_args() + + # Do nothing if service is not configured + c = Config() + if not c.exists_effective('service snmp v3'): + print("SNMP v3 is not configured") + sys.exit(0) + + data = { + 'group': [], + 'trap': [], + 'user': [], + 'view': [] + } + + if c.exists_effective('service snmp v3 group'): + for g in c.list_effective_nodes('service snmp v3 group'): + group = { + 'name': g, + 'mode': '', + 'view': '' + } + group['mode'] = c.return_effective_value('service snmp v3 group {0} mode'.format(g)) + group['view'] = c.return_effective_value('service snmp v3 group {0} view'.format(g)) + + data['group'].append(group) + + if c.exists_effective('service snmp v3 user'): + for u in c.list_effective_nodes('service snmp v3 user'): + user = { + 'name' : u, + 'mode' : '', + 'auth' : '', + 'priv' : '', + 'group': '' + } + user['mode'] = c.return_effective_value('service snmp v3 user {0} mode'.format(u)) + user['auth'] = c.return_effective_value('service snmp v3 user {0} auth type'.format(u)) + user['priv'] = c.return_effective_value('service snmp v3 user {0} privacy type'.format(u)) + user['group'] = c.return_effective_value('service snmp v3 user {0} group'.format(u)) + + data['user'].append(user) + + if c.exists_effective('service snmp v3 view'): + for v in c.list_effective_nodes('service snmp v3 view'): + view = { + 'name': v, + 'oids': [] + } + view['oids'] = c.list_effective_nodes('service snmp v3 view {0} oid'.format(v)) + + data['view'].append(view) + + if c.exists_effective('service snmp v3 trap-target'): + for t in c.list_effective_nodes('service snmp v3 trap-target'): + trap = { + 'name' : t, + 'port' : '', + 'proto': '', + 'auth' : '', + 'priv' : '', + 'type' : '', + 'engID': '', + 'user' : '' + } + trap['port'] = c.return_effective_value('service snmp v3 trap-target {0} port'.format(t)) + trap['proto'] = c.return_effective_value('service snmp v3 trap-target {0} protocol'.format(t)) + trap['auth'] = c.return_effective_value('service snmp v3 trap-target {0} auth type'.format(t)) + trap['priv'] = c.return_effective_value('service snmp v3 trap-target {0} privacy type'.format(t)) + trap['type'] = c.return_effective_value('service snmp v3 trap-target {0} type'.format(t)) + trap['engID'] = c.return_effective_value('service snmp v3 trap-target {0} engineid'.format(t)) + trap['user'] = c.return_effective_value('service snmp v3 trap-target {0} user'.format(t)) + + data['trap'].append(trap) + + print(data) + if args.all: + # Special case, print all templates ! + tmpl = jinja2.Template(GROUP_OUTP_TMPL_SRC) + print(tmpl.render(data)) + tmpl = jinja2.Template(TRAPTGT_OUTP_TMPL_SRC) + print(tmpl.render(data)) + tmpl = jinja2.Template(USER_OUTP_TMPL_SRC) + print(tmpl.render(data)) + tmpl = jinja2.Template(VIEW_OUTP_TMPL_SRC) + print(tmpl.render(data)) + + elif args.group: + tmpl = jinja2.Template(GROUP_OUTP_TMPL_SRC) + print(tmpl.render(data)) + + elif args.trap: + tmpl = jinja2.Template(TRAPTGT_OUTP_TMPL_SRC) + print(tmpl.render(data)) + + elif args.user: + tmpl = jinja2.Template(USER_OUTP_TMPL_SRC) + print(tmpl.render(data)) + + elif args.view: + tmpl = jinja2.Template(VIEW_OUTP_TMPL_SRC) + print(tmpl.render(data)) + + else: + parser.print_help() + + sys.exit(1) diff --git a/src/op_mode/snmp_v3_showcerts.sh b/src/op_mode/snmp_v3_showcerts.sh new file mode 100755 index 0000000..015b2e6 --- /dev/null +++ b/src/op_mode/snmp_v3_showcerts.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +files=`sudo ls /etc/snmp/tls/certs/ 2> /dev/null`; +if [ -n "$files" ]; then + sudo /usr/bin/net-snmp-cert showcerts --subject --fingerprint +else + echo "You don't have any certificates. Put it in '/etc/snmp/tls/certs/' folder." +fi diff --git a/src/op_mode/version.py b/src/op_mode/version.py new file mode 100755 index 0000000..ce3b3b5 --- /dev/null +++ b/src/op_mode/version.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2016 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 sys +import subprocess +import argparse +import json + +import pystache + +import vyos.version +import vyos.limericks + + +parser = argparse.ArgumentParser() +parser.add_argument("-a", "--all", action="store_true", help="Include individual package versions") +parser.add_argument("-f", "--funny", action="store_true", help="Add something funny to the output") +parser.add_argument("-j", "--json", action="store_true", help="Produce JSON output") + +def read_file(name): + try: + with open (name, "r") as f: + data = f.read() + return data.strip() + except: + # This works since we only read /sys/class/* stuff + # with this function + return "Unknown" + +version_output_tmpl = """ +Version: VyOS {{version}} +Built by: {{built_by}} +Built on: {{built_on}} +Build ID: {{build_id}} + +Architecture: {{system_arch}} +Boot via: {{boot_via}} +System type: {{system_type}} + +Hardware vendor: {{hardware_vendor}} +Hardware model: {{hardware_model}} +Hardware S/N: {{hardware_serial}} +Hardware UUID: {{hardware_uuid}} + +Copyright: VyOS maintainers and contributors + +""" + +if __name__ == '__main__': + args = parser.parse_args() + + version_data = vyos.version.get_version_data() + + # Get system architecture (well, kernel architecture rather) + version_data['system_arch'] = subprocess.check_output('uname -m', shell=True).decode().strip() + + + # Get hypervisor name, if any + system_type = "bare metal" + try: + hypervisor = subprocess.check_output('hvinfo 2>/dev/null', shell=True).decode().strip() + system_type = "{0} guest".format(hypervisor) + except subprocess.CalledProcessError: + # hvinfo returns 1 if it cannot detect any hypervisor + pass + version_data['system_type'] = system_type + + + # Get boot type, it can be livecd, installed image, or, possible, a system installed + # via legacy "install system" mechanism + # In installed images, the squashfs image file is named after its image version, + # while on livecd it's just "filesystem.squashfs", that's how we tell a livecd boot + # from an installed image + boot_via = "installed image" + if subprocess.call(""" grep -e '^overlay.*/filesystem.squashfs' /proc/mounts >/dev/null""", shell=True) == 0: + boot_via = "livecd" + elif subprocess.call(""" grep '^overlay /' /proc/mounts >/dev/null """, shell=True) != 0: + boot_via = "legacy non-image installation" + version_data['boot_via'] = boot_via + + + # Get hardware details from DMI + version_data['hardware_vendor'] = read_file('/sys/class/dmi/id/sys_vendor') + version_data['hardware_model'] = read_file('/sys/class/dmi/id/product_name') + + # These two assume script is run as root, normal users can't access those files + version_data['hardware_serial'] = read_file('/sys/class/dmi/id/subsystem/id/product_serial') + version_data['hardware_uuid'] = read_file('/sys/class/dmi/id/subsystem/id/product_uuid') + + + if args.json: + print(json.dumps(version_data)) + sys.exit(0) + else: + output = pystache.render(version_output_tmpl, version_data).strip() + print(output) + + if args.all: + print("Package versions:") + os.system("dpkg -l") + + if args.funny: + print(vyos.limericks.get_random()) diff --git a/src/tests/helper.py b/src/tests/helper.py new file mode 100644 index 0000000..a7e4f20 --- /dev/null +++ b/src/tests/helper.py @@ -0,0 +1,27 @@ +#!/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/>. +# +# + +import sys +import importlib.util + + +def prepare_module(file_path='', module_name=''): + spec = importlib.util.spec_from_file_location(module_name, file_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + sys.modules[module_name] = module diff --git a/src/tests/test_host_name.py b/src/tests/test_host_name.py new file mode 100644 index 0000000..8c5210d --- /dev/null +++ b/src/tests/test_host_name.py @@ -0,0 +1,130 @@ +#!/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/>. +# +# + +import os +import tempfile +import unittest +from unittest import TestCase, mock + +from vyos import ConfigError +try: + from src.conf_mode import host_name +except ModuleNotFoundError: # for unittest.main() + import sys + sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) + from src.conf_mode import host_name + + +class TestHostName(TestCase): + + def test_get_config(self): + tests = [ + {'name': 'empty_hostname_and_domain', + 'host-name': '', + 'domain-name': '', + 'expected': {"hostname": 'vyos', "domain": '', "fqdn": 'vyos'}}, + {'name': 'empty_hostname', + 'host-name': '', + 'domain-name': 'localdomain', + 'expected': {"hostname": 'vyos', "domain": 'localdomain', "fqdn": 'vyos.localdomain'}}, + {'name': 'has_hostname', + 'host-name': 'router', + 'domain-name': '', + 'expected': {"hostname": 'router', "domain": '', "fqdn": 'router'}}, + {'name': 'has_hostname_and_domain', + 'host-name': 'router', + 'domain-name': 'localdomain', + 'expected': {"hostname": 'router', "domain": 'localdomain', "fqdn": 'router.localdomain'}}, + ] + for t in tests: + def mocked_return_value(path, default=None): + return t[path.split()[1]] + + with self.subTest(msg=t['name'], hostname=t['host-name'], domain=t['domain-name'], expected=t['expected']): + with mock.patch('vyos.config.Config.return_value', side_effect=mocked_return_value): + actual = host_name.get_config() + self.assertEqual(actual, t['expected']) + + + def test_verify(self): + tests = [ + {'name': 'valid_hostname', + 'config': {"hostname": 'vyos', "domain": 'localdomain', "fqdn": 'vyos.localdomain'}, + 'expected': None}, + {'name': 'invalid_hostname', + 'config': {"hostname": 'vyos..', "domain": '', "fqdn": ''}, + 'expected': ConfigError}, + {'name': 'invalid_hostname_length', + 'config': {"hostname": 'a'*64, "domain": '', "fqdn": ''}, + 'expected': ConfigError} + ] + for t in tests: + with self.subTest(msg=t['name'], config=t['config'], expected=t['expected']): + if t['expected'] is not None: + with self.assertRaises(t['expected']): + host_name.verify(t['config']) + else: + host_name.verify(t['config']) + + def test_generate(self): + tests = [ + {'name': 'has_old_entry', + 'has_old_entry': True, + 'config': {"hostname": 'router', "domain": 'localdomain', "fqdn": 'router.localdomain'}, + 'expected': ['127.0.1.1', 'router.localdomain']}, + {'name': 'no_old_entry', + 'has_old_entry': False, + 'config': {"hostname": 'router', "domain": 'localdomain', "fqdn": 'router.localdomain'}, + 'expected': ['127.0.1.1', 'router.localdomain']}, + ] + for t in tests: + with self.subTest(msg=t['name'], config=t['config'], has_old_entry=t['has_old_entry'], expected=t['expected']): + m = mock.MagicMock(return_value=b'debian') + with mock.patch('subprocess.check_output', m): + host_name.hosts_file = tempfile.mkstemp()[1] + if t['has_old_entry']: + with open(host_name.hosts_file, 'w') as f: + f.writelines(['\n127.0.1.1 {} # VyOS entry'.format('debian')]) + host_name.generate(t['config']) + if len(t['expected']) > 0: + self.assertTrue(os.path.isfile(host_name.hosts_file)) + with open(host_name.hosts_file) as f: + actual = f.read() + self.assertEqual( + t['expected'], actual.splitlines()[1].split()[0:2]) + os.remove(host_name.hosts_file) + else: + self.assertFalse(os.path.isfile(host_name.hosts_file)) + + + def test_apply(self): + tests = [ + {'name': 'valid_hostname', + 'config': {"hostname": 'router', "domain": 'localdomain', "fqdn": 'router.localdomain'}, + 'expected': [mock.call('hostnamectl set-hostname --static router.localdomain'), + mock.call('systemctl restart rsyslog.service')]} + ] + for t in tests: + with self.subTest(msg=t['name'], c=t['config'], expected=t['expected']): + with mock.patch('os.system') as os_system: + host_name.apply(t['config']) + os_system.assert_has_calls(t['expected']) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/tests/test_task_scheduler.py b/src/tests/test_task_scheduler.py new file mode 100644 index 0000000..084bd86 --- /dev/null +++ b/src/tests/test_task_scheduler.py @@ -0,0 +1,130 @@ +#!/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/>. +# +# + +import os +import tempfile +import unittest + +from vyos import ConfigError +try: + from src.conf_mode import task_scheduler +except ModuleNotFoundError: # for unittest.main() + import sys + sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) + from src.conf_mode import task_scheduler + + +class TestUpdateCrontab(unittest.TestCase): + + def test_verify(self): + tests = [ + {'name': 'one_task', + 'tasks': [{'name': 'aaa', 'interval': '60m', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': None + }, + {'name': 'has_interval_and_spec', + 'tasks': [{'name': 'aaa', 'interval': '60m', 'spec': '0 * * * *', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': ConfigError + }, + {'name': 'has_no_interval_and_spec', + 'tasks': [{'name': 'aaa', 'interval': '', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': ConfigError + }, + {'name': 'invalid_interval', + 'tasks': [{'name': 'aaa', 'interval': '1y', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': ConfigError + }, + {'name': 'invalid_interval_min', + 'tasks': [{'name': 'aaa', 'interval': '61m', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': ConfigError + }, + {'name': 'invalid_interval_hour', + 'tasks': [{'name': 'aaa', 'interval': '25h', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': ConfigError + }, + {'name': 'invalid_interval_day', + 'tasks': [{'name': 'aaa', 'interval': '32d', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': ConfigError + }, + {'name': 'no_executable', + 'tasks': [{'name': 'aaa', 'interval': '60m', 'spec': '', 'executable': '', 'args': ''}], + 'expected': ConfigError + }, + {'name': 'invalid_executable', + 'tasks': [{'name': 'aaa', 'interval': '60m', 'spec': '', 'executable': '/bin/aaa', 'args': ''}], + 'expected': ConfigError + } + ] + for t in tests: + with self.subTest(msg=t['name'], tasks=t['tasks'], expected=t['expected']): + if t['expected'] is not None: + with self.assertRaises(t['expected']): + task_scheduler.verify(t['tasks']) + else: + task_scheduler.verify(t['tasks']) + + def test_generate(self): + tests = [ + {'name': 'zero_task', + 'tasks': [], + 'expected': [] + }, + {'name': 'one_task', + 'tasks': [{'name': 'aaa', 'interval': '60m', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': [ + '### Generated by vyos-update-crontab.py ###', + '*/60 * * * * root sg vyattacfg \"/bin/ls -l\"'] + }, + {'name': 'one_task_with_hour', + 'tasks': [{'name': 'aaa', 'interval': '10h', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': [ + '### Generated by vyos-update-crontab.py ###', + '0 */10 * * * root sg vyattacfg \"/bin/ls -l\"'] + }, + {'name': 'one_task_with_day', + 'tasks': [{'name': 'aaa', 'interval': '10d', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}], + 'expected': [ + '### Generated by vyos-update-crontab.py ###', + '0 0 */10 * * root sg vyattacfg \"/bin/ls -l\"'] + }, + {'name': 'multiple_tasks', + 'tasks': [{'name': 'aaa', 'interval': '60m', 'spec': '', 'executable': '/bin/ls', 'args': '-l'}, + {'name': 'bbb', 'interval': '', 'spec': '0 0 * * *', 'executable': '/bin/ls', 'args': '-ltr'} + ], + 'expected': [ + '### Generated by vyos-update-crontab.py ###', + '*/60 * * * * root sg vyattacfg \"/bin/ls -l\"', + '0 0 * * * root sg vyattacfg \"/bin/ls -ltr\"'] + } + ] + for t in tests: + with self.subTest(msg=t['name'], tasks=t['tasks'], expected=t['expected']): + task_scheduler.crontab_file = tempfile.mkstemp()[1] + task_scheduler.generate(t['tasks']) + if len(t['expected']) > 0: + self.assertTrue(os.path.isfile(task_scheduler.crontab_file)) + with open(task_scheduler.crontab_file) as f: + actual = f.read() + self.assertEqual(t['expected'], actual.splitlines()) + os.remove(task_scheduler.crontab_file) + else: + self.assertFalse(os.path.isfile(task_scheduler.crontab_file)) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/utils/initial-setup b/src/utils/initial-setup new file mode 100644 index 0000000..37fc457 --- /dev/null +++ b/src/utils/initial-setup @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +import argparse + +import vyos.configtree + + +parser = argparse.ArgumentParser() + +parser.add_argument("--ssh", help="Enable SSH", action="store_true") +parser.add_argument("--ssh-port", help="SSH port", type=int, action="store", default=22) + +parser.add_argument("--intf-address", help="Set interface address", type=str, action="append") + +parser.add_argument("config_file", help="Configuration file to modify", type=str) + +args = parser.parse_args() + +# Load the config file +with open(args.config_file, 'r') as f: + config_file = f.read() + +config = vyos.configtree.ConfigTree(config_file) + + +# Interface names and addresses are comma-separated, +# we need to split them +intf_addrs = list(map(lambda s: s.split(","), args.intf_address)) + +# Enable SSH, if requested +if args.ssh: + config.set(["service", "ssh", "port"], value=str(args.ssh_port)) + +# Assign addresses to interfaces +if intf_addrs: + for a in intf_addrs: + config.set(["interfaces", "ethernet", a[0], "address"], value=a[1]) + config.set_tag(["interfaces", "ethernet"]) + +print( config.to_string() ) diff --git a/src/utils/vyos-config-to-commands b/src/utils/vyos-config-to-commands new file mode 100755 index 0000000..8b50f7c --- /dev/null +++ b/src/utils/vyos-config-to-commands @@ -0,0 +1,29 @@ +#!/usr/bin/python3 + +import sys + +from signal import signal, SIGPIPE, SIG_DFL +from vyos.configtree import ConfigTree + +signal(SIGPIPE,SIG_DFL) + +config_string = None +if (len(sys.argv) == 1): + # If no argument given, act as a pipe + config_string = sys.stdin.read() +else: + file_name = sys.argv[1] + try: + with open(file_name, 'r') as f: + config_string = f.read() + except OSError as e: + print("Could not read config file {0}: {1}".format(file_name, e), file=sys.stderr) + +try: + config = ConfigTree(config_string) + commands = config.to_commands() +except ValueError as e: + print("Could not parse the config file: {0}".format(e), file=sys.stderr) + sys.exit(1) + +print(commands) diff --git a/src/validators/interface-address b/src/validators/interface-address new file mode 100755 index 0000000..4c20395 --- /dev/null +++ b/src/validators/interface-address @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-ipv4-host $1 || ipaddrcheck --is-ipv6-host $1 diff --git a/src/validators/ip-address b/src/validators/ip-address new file mode 100755 index 0000000..51fb72c --- /dev/null +++ b/src/validators/ip-address @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-any-single $1 diff --git a/src/validators/ip-host b/src/validators/ip-host new file mode 100755 index 0000000..f2906e8 --- /dev/null +++ b/src/validators/ip-host @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-any-host $1 diff --git a/src/validators/ip-prefix b/src/validators/ip-prefix new file mode 100755 index 0000000..e58aad3 --- /dev/null +++ b/src/validators/ip-prefix @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-any-net $1 diff --git a/src/validators/ipv4-address b/src/validators/ipv4-address new file mode 100755 index 0000000..872a764 --- /dev/null +++ b/src/validators/ipv4-address @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-ipv4-single $1 diff --git a/src/validators/ipv4-host b/src/validators/ipv4-host new file mode 100755 index 0000000..f42feff --- /dev/null +++ b/src/validators/ipv4-host @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-ipv4-host $1 diff --git a/src/validators/ipv4-prefix b/src/validators/ipv4-prefix new file mode 100755 index 0000000..8ec8a2c --- /dev/null +++ b/src/validators/ipv4-prefix @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-ipv4-net $1 diff --git a/src/validators/ipv6-address b/src/validators/ipv6-address new file mode 100755 index 0000000..e5d68d7 --- /dev/null +++ b/src/validators/ipv6-address @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-ipv6-single $1 diff --git a/src/validators/ipv6-host b/src/validators/ipv6-host new file mode 100755 index 0000000..f7a7450 --- /dev/null +++ b/src/validators/ipv6-host @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-ipv6-host $1 diff --git a/src/validators/ipv6-prefix b/src/validators/ipv6-prefix new file mode 100755 index 0000000..e436163 --- /dev/null +++ b/src/validators/ipv6-prefix @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-ipv6-net $1 diff --git a/src/validators/numeric b/src/validators/numeric new file mode 100755 index 0000000..58a4fac --- /dev/null +++ b/src/validators/numeric @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +# +# numeric value validator +# +# Copyright (C) 2017 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 +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; If not, see <http://www.gnu.org/licenses/>. + +import sys +import argparse +import re + +parser = argparse.ArgumentParser() +parser.add_argument("-f", "--float", action="store_true", help="Accept floating point values") +group = parser.add_mutually_exclusive_group() +group.add_argument("-r", "--range", type=str, help="Check if the number is within range (inclusive), example: 1024-65535") +group.add_argument("-n", "--non-negative", action="store_true", help="") +parser.add_argument("number", type=str, help="Number to validate") + +args = parser.parse_args() + +# Try to load the argument +number = None +if args.float: + try: + number = float(args.number) + except: + print("{0} is not a valid floating point number".format(args.number), file=sys.stderr) + sys.exit(1) +else: + try: + number = int(args.number) + except: + print("{0} is not a valid integer number".format(args.number), file=sys.stderr) + sys.exit(1) + +if args.range: + try: + lower, upper = re.match(r'(\d+)\s*\-\s*(\d+)', args.range).groups() + lower, upper = int(lower), int(upper) + except: + print("{0} is not a valid number range",format(args.range), file=sys.stderr) + sys.exit(1) + + if (number < lower) or (number > upper): + print("Number {0} is not in the {1} range".format(number, args.range), file=sys.stderr) + sys.exit(1) +elif args.non_negative: + if number < 0: + print("Number should be non-negative", file=sys.stderr) + sys.exit(1) |