diff --git a/debian/control b/debian/control index 70bf7a61c..04b228737 100644 --- a/debian/control +++ b/debian/control @@ -1,44 +1,45 @@ Source: vyos-1x Section: contrib/net Priority: extra Maintainer: VyOS Package Maintainers <maintainers@vyos.net> Build-Depends: debhelper (>= 9), quilt, python3, python3-setuptools, quilt, python3-lxml, python3-nose, python3-coverage Standards-Version: 3.9.6 Package: vyos-1x Architecture: all Depends: python3, ${python3:Depends}, python3-netifaces, python3-jinja2, python3-pystache, python3-psutil, python3-tabulate, ipaddrcheck, tcpdump, bmon, hvinfo, file, lsscsi, pciutils, usbutils, snmp, snmpd, openssh-server, ntp, ntpdate, iputils-arping, libvyosconfig0, beep, keepalived (>=2.0.5), wireguard, + tftpd-hpa, ${shlibs:Depends}, ${misc:Depends} Description: VyOS configuration scripts and data VyOS configuration scripts, interface definitions, and everything diff --git a/interface-definitions/tftp-server.xml b/interface-definitions/tftp-server.xml new file mode 100644 index 000000000..2874b034c --- /dev/null +++ b/interface-definitions/tftp-server.xml @@ -0,0 +1,57 @@ +<?xml version="1.0"?> +<!-- TFTP configuration --> +<interfaceDefinition> + <node name="service"> + <children> + <node name="tftp-server" owner="${vyos_conf_scripts_dir}/tftp_server.py"> + <properties> + <help>Trivial File Transfer Protocol (TFTP) server</help> + <priority>990</priority> + </properties> + <children> + <leafNode name="directory"> + <properties> + <help>Folder containing files served by TFTP [REQUIRED]</help> + </properties> + </leafNode> + <leafNode name="allow-upload"> + <properties> + <help>Allow TFTP file uploads</help> + <valueless/> + </properties> + </leafNode> + <leafNode name="port"> + <properties> + <help>Port for TFTP service</help> + <valueHelp> + <format>1-65535</format> + <description>Numeric IP port (default: 69)</description> + </valueHelp> + <constraint> + <validator name="numeric" argument="--range 1-65535"/> + </constraint> + </properties> + </leafNode> + <leafNode name="listen-address"> + <properties> + <help>Addresses for TFTP server to listen [REQUIRED]</help> + <valueHelp> + <format>ipv4</format> + <description>TFTP IPv4 listen address</description> + </valueHelp> + <valueHelp> + <format>ipv6</format> + <description>TFTP IPv6 listen address</description> + </valueHelp> + <multi/> + <constraint> + <validator name="ipv4-address"/> + <validator name="ipv6-address"/> + </constraint> + </properties> + </leafNode> + </children> + </node> + </children> + </node> +</interfaceDefinition> diff --git a/src/conf_mode/ntp.py b/src/conf_mode/ntp.py index b618cbd89..8533411cc 100755 --- a/src/conf_mode/ntp.py +++ b/src/conf_mode/ntp.py @@ -1,173 +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') + os.system('sudo systemctl restart ntp.service') else: # NTP support is removed in the commit - os.system('sudo /usr/sbin/invoke-rc.d ntp stop') + os.system('sudo systemctl stop ntp.service') 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/ssh.py b/src/conf_mode/ssh.py index f1ac19473..beca7bb9a 100755 --- a/src/conf_mode/ssh.py +++ b/src/conf_mode/ssh.py @@ -1,255 +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") + os.system("sudo systemctl restart ssh.service") else: # SSH access is removed in the commit - os.system("sudo systemctl stop ssh") + os.system("sudo systemctl stop ssh.service") 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/tftp_server.py b/src/conf_mode/tftp_server.py new file mode 100755 index 000000000..8133ed215 --- /dev/null +++ b/src/conf_mode/tftp_server.py @@ -0,0 +1,159 @@ +#!/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 stat +import pwd + +import jinja2 +import ipaddress +import netifaces + +from vyos.config import Config +from vyos import ConfigError + +config_file = r'/etc/default/tftpd-hpa' + +# Please be careful if you edit the template. +config_tmpl = """ +### Autogenerated by tftp_server.py ### + +# See manual at https://linux.die.net/man/8/tftpd + +TFTP_USERNAME="tftp" +TFTP_DIRECTORY="{{ directory }}" +{% if listen_ipv4 and listen_ipv6 -%} +TFTP_ADDRESS="{% for a in listen_ipv4 -%}{{ a }}:{{ port }}{{- " --address " if not loop.last -}}{% endfor -%} {% for a in listen_ipv6 %} --address [{{ a }}]:{{ port }}{% endfor -%}" +{% elif listen_ipv4 -%} +TFTP_ADDRESS="{% for a in listen_ipv4 -%}{{ a }}:{{ port }}{{- " --address " if not loop.last -}}{% endfor %} -4" +{% elif listen_ipv6 -%} +TFTP_ADDRESS="{% for a in listen_ipv6 -%}[{{ a }}]:{{ port }}{{- " --address " if not loop.last -}}{% endfor %} -6" +{%- endif %} + +TFTP_OPTIONS="--secure {% if allow_upload %}--create --umask 002{% endif %}" +""" + +default_config_data = { + 'directory': '', + 'allow_upload': False, + 'port': '69', + 'listen_ipv4': [], + 'listen_ipv6': [] +} + +# Verify if an IP address is assigned to any interface, IPv4 and IPv6 +def addrok(ipaddr, ipversion): + for interface in netifaces.interfaces(): + # Retrieve IP address of network interfaces + if ipversion in netifaces.ifaddresses(interface).keys(): + for addr in netifaces.ifaddresses(interface)[ipversion]: + if addr['addr'] == ipaddr: + return True + + return False + +def get_config(): + tftpd = default_config_data + conf = Config() + if not conf.exists('service tftp-server'): + return None + else: + conf.set_level('service tftp-server') + + if conf.exists('directory'): + tftpd['directory'] = conf.return_value('directory') + + if conf.exists('allow-upload'): + tftpd['allow_upload'] = True + + if conf.exists('port'): + tftpd['port'] = conf.return_value('port') + + if conf.exists('listen-address'): + for addr in conf.return_values('listen-address'): + if (ipaddress.ip_address(addr).version == 4): + tftpd['listen_ipv4'].append(addr) + + if (ipaddress.ip_address(addr).version == 6): + tftpd['listen_ipv6'].append(addr) + + return tftpd + +def verify(tftpd): + # bail out early - looks like removal from running config + if tftpd is None: + return None + + # Configuring allowed clients without a server makes no sense + if not tftpd['directory']: + raise ConfigError('TFTP root directory must be configured!') + + if not (tftpd['listen_ipv4'] or tftpd['listen_ipv6']): + raise ConfigError('TFTP server listen address must be configured!') + + for address in tftpd['listen_ipv4']: + if not addrok(address, netifaces.AF_INET): + raise ConfigError('TFTP server listen address "{0}" not configured on this system.'.format(address)) + + for address in tftpd['listen_ipv6']: + if not addrok(address, netifaces.AF_INET6): + raise ConfigError('TFTP server listen address "{0}" not configured on this system.'.format(address)) + + return None + +def generate(tftpd): + # bail out early - looks like removal from running config + if tftpd is None: + return None + + tmpl = jinja2.Template(config_tmpl) + config_text = tmpl.render(tftpd) + with open(config_file, 'w') as f: + f.write(config_text) + + return None + +def apply(tftpd): + if tftpd is not None: + + tftp_root = tftpd['directory'] + if not os.path.exists(tftp_root): + os.makedirs(tftp_root) + os.chmod(tftp_root, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH) + # get uid for user 'snmp' + tftp_uid = pwd.getpwnam('tftp').pw_uid + os.chown(tftp_root, tftp_uid, -1) + + os.system('sudo systemctl restart tftpd-hpa.service') + else: + # TFTP server support is removed in the commit + os.system('sudo systemctl stop tftpd-hpa.service') + 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)