diff options
Diffstat (limited to 'src')
-rwxr-xr-x | src/completion/list_interfaces.py | 9 | ||||
-rwxr-xr-x | src/conf_mode/accel_l2tp.py | 529 | ||||
-rwxr-xr-x | src/conf_mode/accel_sstp.py | 469 | ||||
-rwxr-xr-x | src/conf_mode/bridge_has_members.py | 85 | ||||
-rwxr-xr-x | src/conf_mode/dhcpv6_relay.py | 9 | ||||
-rwxr-xr-x | src/conf_mode/http-api.py | 13 | ||||
-rwxr-xr-x | src/conf_mode/https.py | 5 | ||||
-rwxr-xr-x | src/conf_mode/interface-bridge.py | 306 | ||||
-rwxr-xr-x | src/conf_mode/interface-wireguard.py (renamed from src/conf_mode/wireguard.py) | 0 | ||||
-rwxr-xr-x | src/conf_mode/ipsec-settings.py | 197 | ||||
-rwxr-xr-x | src/conf_mode/protocols_bfd.py | 179 | ||||
-rwxr-xr-x | src/migration-scripts/interfaces/0-to-1 | 85 | ||||
-rwxr-xr-x | src/op_mode/show_vpn_ra.py | 58 | ||||
-rwxr-xr-x | src/op_mode/snmp_ifmib.py | 10 | ||||
-rwxr-xr-x | src/services/vyos-http-api-server | 14 | ||||
-rwxr-xr-x | src/validators/cidr | 3 | ||||
-rwxr-xr-x | src/validators/file-exists | 62 | ||||
-rwxr-xr-x | src/validators/ip-cidr | 3 |
18 files changed, 1872 insertions, 164 deletions
diff --git a/src/completion/list_interfaces.py b/src/completion/list_interfaces.py index a4968c52f..66432af19 100755 --- a/src/completion/list_interfaces.py +++ b/src/completion/list_interfaces.py @@ -10,6 +10,7 @@ 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") +group.add_argument("-br", "--bridgeable", action="store_true", help="List all bridgeable interfaces") args = parser.parse_args() @@ -25,6 +26,14 @@ elif args.broadcast: bridge = vyos.interfaces.list_interfaces_of_type("bridge") bond = vyos.interfaces.list_interfaces_of_type("bonding") interfaces = eth + bridge + bond +elif args.bridgeable: + eth = vyos.interfaces.list_interfaces_of_type("ethernet") + bond = vyos.interfaces.list_interfaces_of_type("bonding") + l2tpv3 = vyos.interfaces.list_interfaces_of_type("l2tpv3") + openvpn = vyos.interfaces.list_interfaces_of_type("openvpn") + vxlan = vyos.interfaces.list_interfaces_of_type("vxlan") + wireless = vyos.interfaces.list_interfaces_of_type("wireless") + interfaces = eth + bond + l2tpv3 + openvpn + vxlan + wireless else: interfaces = vyos.interfaces.list_interfaces() diff --git a/src/conf_mode/accel_l2tp.py b/src/conf_mode/accel_l2tp.py new file mode 100755 index 000000000..3af8b7958 --- /dev/null +++ b/src/conf_mode/accel_l2tp.py @@ -0,0 +1,529 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2019 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 re +import subprocess +import jinja2 +import socket +import time +import syslog as sl + +from vyos.config import Config +from vyos import ConfigError + +pidfile = r'/var/run/accel_l2tp.pid' +l2tp_cnf_dir = r'/etc/accel-ppp/l2tp' +chap_secrets = l2tp_cnf_dir + '/chap-secrets' +l2tp_conf = l2tp_cnf_dir + '/l2tp.config' +# accel-pppd -d -c /etc/accel-ppp/l2tp/l2tp.config -p /var/run/accel_l2tp.pid + +### config path creation +if not os.path.exists(l2tp_cnf_dir): + os.makedirs(l2tp_cnf_dir) + sl.syslog(sl.LOG_NOTICE, l2tp_cnf_dir + " created") + +l2tp_config = ''' +### generated by accel_l2tp.py ### +[modules] +log_syslog +l2tp +chap-secrets +{% for proto in authentication['auth_proto']: %} +{{proto}} +{% endfor%} +{% if authentication['mode'] == 'radius' %} +radius +{% endif -%} +ippool +shaper +ipv6pool +ipv6_nd +ipv6_dhcp + +[core] +thread-count={{thread_cnt}} + +[log] +syslog=accel-l2tp,daemon +copy=1 +level=5 + +{% if dns %} +[dns] +{% if dns[0] %} +dns1={{dns[0]}} +{% endif %} +{% if dns[1] %} +dns2={{dns[1]}} +{% endif %} +{% endif -%} + +{% if dnsv6 %} +[ipv6-dns] +{% for srv in dnsv6: %} +{{srv}} +{% endfor %} +{% endif %} + +{% if wins %} +[wins] +{% if wins[0] %} +wins1={{wins[0]}} +{% endif %} +{% if wins[1] %} +wins2={{wins[1]}} +{% endif %} +{% endif -%} + +[l2tp] +verbose=1 +ppp-max-mtu={{mtu}} +mppe={{authentication['mppe']}} +{% if outside_addr %} +bind={{outside_addr}} +{% endif %} +{% if lns_shared_secret %} +secret={{lns_shared_secret}} +{% endif %} + +[client-ip-range] +0.0.0.0/0 + +{% if (client_ip_pool) or (client_ip_subnets) %} +[ip-pool] +{% if client_ip_pool %} +{{client_ip_pool}} +{% endif -%} +{% if client_ip_subnets %} +{% for sn in client_ip_subnets %} +{{sn}} +{% endfor -%} +{% endif %} +{% endif %} +{% if outside_nexthop %} +gw-ip-address={{outside_nexthop}} +{% endif %} + +{% if authentication['mode'] == 'local' %} +[chap-secrets] +chap-secrets=/etc/accel-ppp/l2tp/chap-secrets +{% endif %} + +[ppp] +verbose=1 +check-ip=1 +single-session=replace +{% if idle_timeout %} +lcp-echo-timeout={{idle_timeout}} +{% endif %} +lcp-echo-interval=30 +{% if ccp_disable %} +ccp=0 +{% endif %} +{% if client_ipv6_pool %} +ipv6=allow +{% endif %} + +{% if authentication['mode'] == 'radius' %} +[radius] +{% for rsrv in authentication['radiussrv']: %} +server={{rsrv}},{{authentication['radiussrv'][rsrv]['secret']}},\ +req-limit={{authentication['radiussrv'][rsrv]['req-limit']}},\ +fail-time={{authentication['radiussrv'][rsrv]['fail-time']}} +{% endfor %} +{% if authentication['radiusopt']['timeout'] %} +timeout={{authentication['radiusopt']['timeout']}} +{% endif %} +{% if authentication['radiusopt']['acct-timeout'] %} +acct-timeout={{authentication['radiusopt']['acct-timeout']}} +{% endif %} +{% if authentication['radiusopt']['max-try'] %} +max-try={{authentication['radiusopt']['max-try']}} +{% endif %} +{% if authentication['radiusopt']['nas-id'] %} +nas-identifier={{authentication['radiusopt']['nas-id']}} +{% endif %} +{% if authentication['radius_source_address'] %} +nas-ip-address={{authentication['radius_source_address']}} +{% endif -%} +{% if authentication['radiusopt']['dae-srv'] %} +dae-server={{authentication['radiusopt']['dae-srv']['ip-addr']}}:\ +{{authentication['radiusopt']['dae-srv']['port']}},\ +{{authentication['radiusopt']['dae-srv']['secret']}} +{% endif -%} +gw-ip-address={{outside_nexthop}} +verbose=1 +{% endif -%} + +{% if client_ipv6_pool %} +[ipv6-pool] +{% for prfx in client_ipv6_pool.prefix: %} +{{prfx}} +{% endfor %} +{% for prfx in client_ipv6_pool.delegate_prefix: %} +delegate={{prfx}} +{% endfor %} +{% endif %} + +{% if client_ipv6_pool['delegate_prefix'] %} +[ipv6-dhcp] +verbose=1 +{% endif %} + +{% if authentication['radiusopt']['shaper'] %} +[shaper] +verbose=1 +attr={{authentication['radiusopt']['shaper']['attr']}} +{% if authentication['radiusopt']['shaper']['vendor'] %} +vendor={{authentication['radiusopt']['shaper']['vendor']}} +{% endif -%} +{% endif %} + +[cli] +tcp=127.0.0.1:2004 +sessions-columns=ifname,username,calling-sid,ip,{{ip6_column}}{{ip6_dp_column}}rate-limit,type,comp,state,rx-bytes,tx-bytes,uptime + +''' + +### l2tp chap secrets +chap_secrets_conf = ''' +# username server password acceptable local IP addresses shaper +{% for user in authentication['local-users'] %} +{% if authentication['local-users'][user]['state'] == 'enabled' %} +{% if (authentication['local-users'][user]['upload']) and (authentication['local-users'][user]['download']) %} +{{user}}\t*\t{{authentication['local-users'][user]['passwd']}}\t{{authentication['local-users'][user]['ip']}}\t\ +{{authentication['local-users'][user]['download']}}/{{authentication['local-users'][user]['upload']}} +{% else %} +{{user}}\t*\t{{authentication['local-users'][user]['passwd']}}\t{{authentication['local-users'][user]['ip']}} +{% endif %} +{% endif %} +{% endfor %} +''' + +### +# inline helper functions +### +# depending on hw and threads, daemon needs a little to start +# if it takes longer than 100 * 0.5 secs, exception is being raised +# not sure if that's the best way to check it, but it worked so far quite well +### +def chk_con(): + cnt = 0 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + while True: + try: + s.connect(("127.0.0.1", 2004)) + break + except ConnectionRefusedError: + time.sleep(0.5) + cnt +=1 + if cnt == 100: + raise("failed to start l2tp server") + break + +### chap_secrets file if auth mode local +def write_chap_secrets(c): + tmpl = jinja2.Template(chap_secrets_conf, trim_blocks=True) + chap_secrets_txt = tmpl.render(c) + old_umask = os.umask(0o077) + open(chap_secrets,'w').write(chap_secrets_txt) + os.umask(old_umask) + sl.syslog(sl.LOG_NOTICE, chap_secrets + ' written') + +def accel_cmd(cmd=''): + if not cmd: + return None + try: + ret = subprocess.check_output(['/usr/bin/accel-cmd','-p','2004',cmd]).decode().strip() + return ret + except: + return 1 + +### +# inline helper functions end +### + +def get_config(): + c = Config() + if not c.exists('vpn l2tp remote-access '): + return None + + c.set_level('vpn l2tp remote-access') + config_data = { + 'authentication' : { + 'mode' : 'local', + 'local-users' : { + }, + 'radiussrv' : {}, + 'radiusopt' : {}, + 'auth_proto' : [], + 'mppe' : 'prefer' + }, + 'outside_addr' : '', + 'outside_nexthop' : '', + 'dns' : [], + 'dnsv6' : [], + 'wins' : [], + 'client_ip_pool' : None, + 'client_ip_subnets' : [], + 'client_ipv6_pool' : {}, + 'mtu' : '1436', + 'ip6_column' : '', + 'ip6_dp_column' : '', + } + + ### general options ### + + if c.exists('dns-servers server-1'): + config_data['dns'].append( c.return_value('dns-servers server-1')) + if c.exists('dns-servers server-2'): + config_data['dns'].append( c.return_value('dns-servers server-2')) + if c.exists('dnsv6-servers'): + for dns6_server in c.return_values('dnsv6-servers'): + config_data['dnsv6'].append(dns6_server) + if c.exists('wins-servers server-1'): + config_data['wins'].append( c.return_value('wins-servers server-1')) + if c.exists('wins-servers server-2'): + config_data['wins'].append( c.return_value('wins-servers server-2')) + if c.exists('outside-address'): + config_data['outside_addr'] = c.return_value('outside-address') + + ### auth local + if c.exists('authentication mode local'): + if c.exists('authentication local-users username'): + for usr in c.list_nodes('authentication local-users username'): + config_data['authentication']['local-users'].update( + { + usr : { + 'passwd' : '', + 'state' : 'enabled', + 'ip' : '*', + 'upload' : None, + 'download' : None + } + } + ) + + if c.exists('authentication local-users username ' + usr + ' password'): + config_data['authentication']['local-users'][usr]['passwd'] = c.return_value('authentication local-users username ' + usr + ' password') + if c.exists('authentication local-users username ' + usr + ' disable'): + config_data['authentication']['local-users'][usr]['state'] = 'disable' + if c.exists('authentication local-users username ' + usr + ' static-ip'): + config_data['authentication']['local-users'][usr]['ip'] = c.return_value('authentication local-users username ' + usr + ' static-ip') + if c.exists('authentication local-users username ' + usr + ' rate-limit download'): + config_data['authentication']['local-users'][usr]['download'] = c.return_value('authentication local-users username ' + usr + ' rate-limit download') + if c.exists('authentication local-users username ' + usr + ' rate-limit upload'): + config_data['authentication']['local-users'][usr]['upload'] = c.return_value('authentication local-users username ' + usr + ' rate-limit upload') + + ### authentication mode radius servers and settings + + if c.exists('authentication mode radius'): + config_data['authentication']['mode'] = 'radius' + rsrvs = c.list_nodes('authentication radius server') + for rsrv in rsrvs: + if c.return_value('authentication radius server ' + rsrv + ' fail-time') == None: + ftime = '0' + else: + ftime = str(c.return_value('authentication radius server ' + rsrv + ' fail-time')) + if c.return_value('authentication radius-server ' + rsrv + ' req-limit') == None: + reql = '0' + else: + reql = str(c.return_value('authentication radius server ' + rsrv + ' req-limit')) + + config_data['authentication']['radiussrv'].update( + { + rsrv : { + 'secret' : c.return_value('authentication radius server ' + rsrv + ' key'), + 'fail-time' : ftime, + 'req-limit' : reql + } + } + ) + ### Source ip address feature + if c.exists('authentication radius source-address'): + config_data['authentication']['radius_source_address'] = c.return_value('authentication radius source-address') + + #### advanced radius-setting + if c.exists('authentication radius acct-timeout'): + config_data['authentication']['radiusopt']['acct-timeout'] = c.return_value('authentication radius acct-timeout') + if c.exists('authentication radius max-try'): + config_data['authentication']['radiusopt']['max-try'] = c.return_value('authentication radius max-try') + if c.exists('authentication radius timeout'): + config_data['authentication']['radiusopt']['timeout'] = c.return_value('authentication radius timeout') + if c.exists('authentication radius nas-identifier'): + config_data['authentication']['radiusopt']['nas-id'] = c.return_value('authentication radius nas-identifier') + if c.exists('authentication radius dae-server'): + # Set default dae-server port if not defined + if c.exists('authentication radius dae-server port'): + dae_server_port = c.return_value('authentication radius dae-server port') + else: + dae_server_port = "3799" + config_data['authentication']['radiusopt'].update( + { + 'dae-srv' : { + 'ip-addr' : c.return_value('authentication radius dae-server ip-address'), + 'port' : dae_server_port, + 'secret' : str(c.return_value('authentication radius dae-server secret')) + } + } + ) + #### filter-id is the internal accel default if attribute is empty + #### set here as default for visibility which may change in the future + if c.exists('authentication radius rate-limit enable'): + if not c.exists('authentication radius rate-limit attribute'): + config_data['authentication']['radiusopt']['shaper'] = { + 'attr' : 'Filter-Id' + } + else: + config_data['authentication']['radiusopt']['shaper'] = { + 'attr' : c.return_value('authentication radius rate-limit attribute') + } + if c.exists('authentication radius rate-limit vendor'): + config_data['authentication']['radiusopt']['shaper']['vendor'] = c.return_value('authentication radius rate-limit vendor') + + if c.exists('client-ip-pool'): + if c.exists('client-ip-pool start') and c.exists('client-ip-pool stop'): + config_data['client_ip_pool'] = c.return_value('client-ip-pool start') + '-' + re.search('[0-9]+$', c.return_value('client-ip-pool stop')).group(0) + + if c.exists('client-ip-pool subnet'): + config_data['client_ip_subnets'] = c.return_values('client-ip-pool subnet') + + if c.exists('client-ipv6-pool prefix'): + config_data['client_ipv6_pool']['prefix'] = c.return_values('client-ipv6-pool prefix') + config_data['ip6_column'] = 'ip6,' + if c.exists('client-ipv6-pool delegate-prefix'): + config_data['client_ipv6_pool']['delegate_prefix'] = c.return_values('client-ipv6-pool delegate-prefix') + config_data['ip6_dp_column'] = 'ip6-dp,' + + if c.exists('mtu'): + config_data['mtu'] = c.return_value('mtu') + + ### gateway address + if c.exists('outside-nexthop'): + config_data['outside_nexthop'] = c.return_value('outside-nexthop') + + if c.exists('authentication require'): + auth_mods = {'pap' : 'pap','chap' : 'auth_chap_md5', 'mschap' : 'auth_mschap_v1', 'mschap-v2' : 'auth_mschap_v2'} + for proto in c.return_values('authentication require'): + config_data['authentication']['auth_proto'].append(auth_mods[proto]) + else: + config_data['authentication']['auth_proto'] = ['auth_mschap_v2'] + + if c.exists('authentication mppe'): + config_data['authentication']['mppe'] = c.return_value('authentication mppe') + + if c.exists('idle'): + config_data['idle_timeout'] = c.return_value('idle') + + ### LNS secret + if c.exists('lns shared-secret'): + config_data['lns_shared_secret'] = c.return_value('lns shared-secret') + + if c.exists('ccp-disable'): + config_data['ccp_disable'] = True + + return config_data + +def verify(c): + if c == None: + return None + + if c['authentication']['mode'] == 'local': + if not c['authentication']['local-users']: + raise ConfigError('l2tp-server authentication local-users required') + for usr in c['authentication']['local-users']: + if not c['authentication']['local-users'][usr]['passwd']: + raise ConfigError('user ' + usr + ' requires a password') + + if c['authentication']['mode'] == 'radius': + if len(c['authentication']['radiussrv']) == 0: + raise ConfigError('radius server required') + for rsrv in c['authentication']['radiussrv']: + if c['authentication']['radiussrv'][rsrv]['secret'] == None: + raise ConfigError('radius server ' + rsrv + ' needs a secret configured') + + ### check for the existence of a client ip pool + if not c['client_ip_pool'] and not c['client_ip_subnets']: + raise ConfigError("set vpn l2tp remote-access client-ip-pool requires subnet or start/stop IP pool") + + if not c['outside_nexthop']: + #raise ConfigError('set vpn l2tp remote-access outside-nexthop required') + print ("WARMING: set vpn l2tp remote-access outside-nexthop required") + + ## check ipv6 + if 'delegate_prefix' in c['client_ipv6_pool'] and not 'prefix' in c['client_ipv6_pool']: + raise ConfigError("\"set vpn l2tp remote-access client-ipv6-pool prefix\" required for delegate-prefix ") + + if len(c['dnsv6']) > 3: + raise ConfigError("Maximum allowed dnsv6-servers addresses is 3") + +def generate(c): + if c == None: + return None + + ### accel-cmd reload doesn't work so any change results in a restart of the daemon + try: + if os.cpu_count() == 1: + c['thread_cnt'] = 1 + else: + c['thread_cnt'] = int(os.cpu_count()/2) + except KeyError: + if os.cpu_count() == 1: + c['thread_cnt'] = 1 + else: + c['thread_cnt'] = int(os.cpu_count()/2) + + tmpl = jinja2.Template(l2tp_config, trim_blocks=True) + config_text = tmpl.render(c) + open(l2tp_conf,'w').write(config_text) + + if c['authentication']['local-users']: + write_chap_secrets(c) + + return c + +def apply(c): + if c == None: + if os.path.exists(pidfile): + accel_cmd('shutdown hard') + if os.path.exists(pidfile): + os.remove(pidfile) + return None + + if not os.path.exists(pidfile): + ret = subprocess.call(['/usr/sbin/accel-pppd','-c',l2tp_conf,'-p',pidfile,'-d']) + chk_con() + if ret !=0 and os.path.exists(pidfile): + os.remove(pidfile) + raise ConfigError('accel-pppd failed to start') + else: + ### if gw ip changes, only restart doesn't work + accel_cmd('restart') + sl.syslog(sl.LOG_NOTICE, "reloading config via daemon restart") + +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/accel_sstp.py b/src/conf_mode/accel_sstp.py new file mode 100755 index 000000000..1317a32db --- /dev/null +++ b/src/conf_mode/accel_sstp.py @@ -0,0 +1,469 @@ +#!/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 re +import subprocess +import jinja2 +import socket +import time +import syslog as sl + +from vyos.config import Config +from vyos import ConfigError + +pidfile = r'/var/run/accel_sstp.pid' +sstp_cnf_dir = r'/etc/accel-ppp/sstp' +chap_secrets = sstp_cnf_dir + '/chap-secrets' +sstp_conf = sstp_cnf_dir + '/sstp.config' +ssl_cert_dir = r'/config/user-data/sstp' + +### config path creation +if not os.path.exists(sstp_cnf_dir): + os.makedirs(sstp_cnf_dir) + sl.syslog(sl.LOG_NOTICE, sstp_cnf_dir + " created") + +if not os.path.exists(ssl_cert_dir): + os.makedirs(ssl_cert_dir) + sl.syslog(sl.LOG_NOTICE, ssl_cert_dir + " created") + +sstp_config = ''' +### generated by accel_sstp.py ### +[modules] +log_syslog +sstp +ippool +shaper +{% if authentication['mode'] == 'local' %} +chap-secrets +{% endif -%} +{% for proto in authentication['auth_proto'] %} +{{proto}} +{% endfor %} +{% if authentication['mode'] == 'radius' %} +radius +{% endif %} + +[core] +thread-count={{thread_cnt}} + +[common] +single-session=replace + +[log] +syslog=accel-sstp,daemon +copy=1 +level=5 + +[client-ip-range] +disable + +[sstp] +verbose=1 +accept=ssl +{% if certs %} +ssl-ca-file=/config/user-data/sstp/{{certs['ca']}} +ssl-pemfile=/config/user-data/sstp/{{certs['server-cert']}} +ssl-keyfile=/config/user-data/sstp/{{certs['server-key']}} +{% endif %} + +{%if ip_pool %} +[ip-pool] +gw-ip-address={{gw}} +{% for sn in ip_pool %} +{{sn}} +{% endfor %} +{% endif %} + +{% if dnsv4 %} +[dns] +{% if dnsv4['primary'] %} +dns1={{dnsv4['primary']}} +{% endif -%} +{% if dnsv4['secondary'] %} +dns2={{dnsv4['secondary']}} +{% endif -%} +{% endif %} + +{% if authentication['mode'] == 'local' %} +[chap-secrets] +chap-secrets=/etc/accel-ppp/sstp/chap-secrets +{% endif %} + +{%- if authentication['mode'] == 'radius' %} +[radius] +verbose=1 +{% for rsrv in authentication['radius-srv']: %} +server={{rsrv}},{{authentication['radius-srv'][rsrv]['secret']}},\ +req-limit={{authentication['radius-srv'][rsrv]['req-limit']}},\ +fail-time={{authentication['radius-srv'][rsrv]['fail-time']}} +{% endfor -%} +{% if authentication['radiusopt']['acct-timeout'] %} +acct-timeout={{authentication['radiusopt']['acct-timeout']}} +{% endif -%} +{% if authentication['radiusopt']['timeout'] %} +timeout={{authentication['radiusopt']['timeout']}} +{% endif -%} +{% if authentication['radiusopt']['max-try'] %} +max-try={{authentication['radiusopt']['max-try']}} +{% endif -%} +{% if authentication['radiusopt']['nas-id'] %} +nas-identifier={{authentication['radiusopt']['nas-id']}} +{% endif -%} +{% if authentication['radiusopt']['nas-ip'] %} +nas-ip-address={{authentication['radiusopt']['nas-ip']}} +{% endif -%} +{% if authentication['radiusopt']['dae-srv'] %} +dae-server={{authentication['radiusopt']['dae-srv']['ip-addr']}}:\ +{{authentication['radiusopt']['dae-srv']['port']}},\ +{{authentication['radiusopt']['dae-srv']['secret']}} +{% endif -%} +{% endif %} + +[ppp] +verbose=1 +check-ip=1 +{% if mtu %} +mtu={{mtu}} +{% endif -%} +{% if ppp['mppe'] %} +mppe={{ppp['mppe']}} +{% endif -%} +{% if ppp['lcp-echo-interval'] %} +lcp-echo-interval={{ppp['lcp-echo-interval']}} +{% endif -%} +{% if ppp['lcp-echo-failure'] %} +lcp-echo-failure={{ppp['lcp-echo-failure']}} +{% endif -%} +{% if ppp['lcp-echo-timeout'] %} +lcp-echo-timeout={{ppp['lcp-echo-timeout']}} +{% endif %} + +{% if authentication['radiusopt']['shaper'] %} +[shaper] +verbose=1 +attr={{authentication['radiusopt']['shaper']['attr']}} +{% if authentication['radiusopt']['shaper']['vendor'] %} +vendor={{authentication['radiusopt']['shaper']['vendor']}} +{% endif -%} +{% endif %} + +[cli] +tcp=127.0.0.1:2005 +''' + +### sstp chap secrets +chap_secrets_conf = ''' +# username server password acceptable local IP addresses shaper +{% for user in authentication['local-users'] %} +{% if authentication['local-users'][user]['state'] == 'enabled' %} +{% if (authentication['local-users'][user]['upload']) and (authentication['local-users'][user]['download']) %} +{{user}}\t*\t{{authentication['local-users'][user]['passwd']}}\t{{authentication['local-users'][user]['ip']}}\t\ +{{authentication['local-users'][user]['download']}}/{{authentication['local-users'][user]['upload']}} +{% else %} +{{user}}\t*\t{{authentication['local-users'][user]['passwd']}}\t{{authentication['local-users'][user]['ip']}} +{% endif %} +{% endif %} +{% endfor %} +''' +### +# inline helper functions +### +# depending on hw and threads, daemon needs a little to start +# if it takes longer than 100 * 0.5 secs, exception is being raised +# not sure if that's the best way to check it, but it worked so far quite well +### +def chk_con(): + cnt = 0 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + while True: + try: + s.connect(("127.0.0.1", 2005)) + s.close() + break + except ConnectionRefusedError: + time.sleep(0.5) + cnt +=1 + if cnt == 100: + raise("failed to start sstp server") + break + +### chap_secrets file if auth mode local +def write_chap_secrets(c): + tmpl = jinja2.Template(chap_secrets_conf, trim_blocks=True) + chap_secrets_txt = tmpl.render(c) + old_umask = os.umask(0o077) + open(chap_secrets,'w').write(chap_secrets_txt) + os.umask(old_umask) + sl.syslog(sl.LOG_NOTICE, chap_secrets + ' written') + +def accel_cmd(cmd=''): + if not cmd: + return None + try: + ret = subprocess.check_output(['/usr/bin/accel-cmd','-p','2005',cmd]).decode().strip() + return ret + except: + return 1 + +#### check ig local-ip is in client pool subnet + + +### +# inline helper functions end +### + +def get_config(): + c = Config() + if not c.exists('service sstp-server'): + return None + + c.set_level('service sstp-server') + + config_data = { + 'authentication' : { + 'local-users' : { + }, + 'mode' : 'local', + 'auth_proto' : [], + 'radius-srv' : {}, + 'radiusopt' : {}, + 'dae-srv' : {} + }, + 'certs' : { + 'ca' : None, + 'server-key' : None, + 'server-cert' : None + }, + 'ip_pool' : [], + 'gw' : None, + 'dnsv4' : {}, + 'mtu' : None, + 'ppp' : {}, + } + + ### local auth + if c.exists('authentication mode local'): + if c.exists('authentication local-users'): + for usr in c.list_nodes('authentication local-users username'): + config_data['authentication']['local-users'].update( + { + usr : { + 'passwd' : None, + 'state' : 'enabled', + 'ip' : '*', + 'upload' : None, + 'download' : None + } + } + ) + if c.exists('authentication local-users username ' + usr + ' password'): + config_data['authentication']['local-users'][usr]['passwd'] = c.return_value('authentication local-users username ' + usr + ' password') + if c.exists('authentication local-users username ' + usr + ' disable'): + config_data['authentication']['local-users'][usr]['state'] = 'disable' + if c.exists('authentication local-users username ' + usr + ' static-ip'): + config_data['authentication']['local-users'][usr]['ip'] = c.return_value('authentication local-users username ' + usr + ' static-ip') + if c.exists('authentication local-users username ' + usr + ' rate-limit download'): + config_data['authentication']['local-users'][usr]['download'] = c.return_value('authentication local-users username ' + usr + ' rate-limit download') + if c.exists('authentication local-users username ' + usr + ' rate-limit upload'): + config_data['authentication']['local-users'][usr]['upload'] = c.return_value('authentication local-users username ' + usr + ' rate-limit upload') + + if c.exists('authentication protocols'): + auth_mods = {'pap' : 'pap','chap' : 'auth_chap_md5', 'mschap' : 'auth_mschap_v1', 'mschap-v2' : 'auth_mschap_v2'} + for proto in c.return_values('authentication protocols'): + config_data['authentication']['auth_proto'].append(auth_mods[proto]) + else: + config_data['authentication']['auth_proto'] = ['auth_mschap_v2'] + + #### RADIUS auth and settings + if c.exists('authentication mode radius'): + config_data['authentication']['mode'] = c.return_value('authentication mode') + if c.exists('authentication radius-server'): + for rsrv in c.list_nodes('authentication radius-server'): + config_data['authentication']['radius-srv'][rsrv] = {} + if c.exists('authentication radius-server ' + rsrv + ' secret'): + config_data['authentication']['radius-srv'][rsrv]['secret'] = c.return_value('authentication radius-server ' + rsrv + ' secret') + else: + config_data['authentication']['radius-srv'][rsrv]['secret'] = None + if c.exists('authentication radius-server ' + rsrv + ' fail-time'): + config_data['authentication']['radius-srv'][rsrv]['fail-time'] = c.return_value('authentication radius-server ' + rsrv + ' fail-time') + else: + config_data['authentication']['radius-srv'][rsrv]['fail-time'] = 0 + if c.exists('authentication radius-server ' + rsrv + ' req-limit'): + config_data['authentication']['radius-srv'][rsrv]['req-limit'] = c.return_value('authentication radius-server ' + rsrv + ' req-limit') + else: + config_data['authentication']['radius-srv'][rsrv]['req-limit'] = 0 + + #### advanced radius-setting + if c.exists('authentication radius-settings'): + if c.exists('authentication radius-settings acct-timeout'): + config_data['authentication']['radiusopt']['acct-timeout'] = c.return_value('authentication radius-settings acct-timeout') + if c.exists('authentication radius-settings max-try'): + config_data['authentication']['radiusopt']['max-try'] = c.return_value('authentication radius-settings max-try') + if c.exists('authentication radius-settings timeout'): + config_data['authentication']['radiusopt']['timeout'] = c.return_value('authentication radius-settings timeout') + if c.exists('authentication radius-settings nas-identifier'): + config_data['authentication']['radiusopt']['nas-id'] = c.return_value('authentication radius-settings nas-identifier') + if c.exists('authentication radius-settings nas-ip-address'): + config_data['authentication']['radiusopt']['nas-ip'] = c.return_value('authentication radius-settings nas-ip-address') + if c.exists('authentication radius-settings dae-server'): + config_data['authentication']['radiusopt'].update( + { + 'dae-srv' : { + 'ip-addr' : c.return_value('authentication radius-settings dae-server ip-address'), + 'port' : c.return_value('authentication radius-settings dae-server port'), + 'secret' : str(c.return_value('authentication radius-settings dae-server secret')) + } + } + ) + if c.exists('authentication radius-settings rate-limit enable'): + if not c.exists('authentication radius-settings rate-limit attribute'): + config_data['authentication']['radiusopt']['shaper'] = { 'attr' : 'Filter-Id' } + else: + config_data['authentication']['radiusopt']['shaper'] = { + 'attr' : c.return_value('authentication radius-settings rate-limit attribute') + } + if c.exists('authentication radius-settings rate-limit vendor'): + config_data['authentication']['radiusopt']['shaper']['vendor'] = c.return_value('authentication radius-settings rate-limit vendor') + + if c.exists('sstp-settings ssl-certs ca'): + config_data['certs']['ca'] = c.return_value('sstp-settings ssl-certs ca') + if c.exists('sstp-settings ssl-certs server-cert'): + config_data['certs']['server-cert'] = c.return_value('sstp-settings ssl-certs server-cert') + if c.exists('sstp-settings ssl-certs server-key'): + config_data['certs']['server-key'] = c.return_value('sstp-settings ssl-certs server-key') + + if c.exists('network-settings client-ip-settings subnet'): + config_data['ip_pool'] = c.return_values('network-settings client-ip-settings subnet') + if c.exists('network-settings client-ip-settings gateway-address'): + config_data['gw'] = c.return_value('network-settings client-ip-settings gateway-address') + if c.exists('network-settings dns-server primary-dns'): + config_data['dnsv4']['primary'] = c.return_value('network-settings dns-server primary-dns') + if c.exists('network-settings dns-server secondary-dns'): + config_data['dnsv4']['secondary'] = c.return_value('network-settings dns-server secondary-dns') + if c.exists('network-settings mtu'): + config_data['mtu'] = c.return_value('network-settings mtu') + + #### ppp + if c.exists('ppp-settings mppe'): + config_data['ppp']['mppe'] = c.return_value('ppp-settings mppe') + if c.exists('ppp-settings lcp-echo-failure'): + config_data['ppp']['lcp-echo-failure'] = c.return_value('ppp-settings lcp-echo-failure') + if c.exists('ppp-settings lcp-echo-interval'): + config_data['ppp']['lcp-echo-interval'] = c.return_value('ppp-settings lcp-echo-interval') + if c.exists('ppp-settings lcp-echo-timeout'): + config_data['ppp']['lcp-echo-timeout'] = c.return_value('ppp-settings lcp-echo-timeout') + + return config_data + +def verify(c): + if c == None: + return None + ### vertify auth settings + if c['authentication']['mode'] == 'local': + if not c['authentication']['local-users']: + raise ConfigError('sstp-server authentication local-users required') + + for usr in c['authentication']['local-users']: + if not c['authentication']['local-users'][usr]['passwd']: + raise ConfigError('user ' + usr + ' requires a password') + ### if up/download is set, check that both have a value + if c['authentication']['local-users'][usr]['upload']: + if not c['authentication']['local-users'][usr]['download']: + raise ConfigError('user ' + usr + ' requires download speed value') + if c['authentication']['local-users'][usr]['download']: + if not c['authentication']['local-users'][usr]['upload']: + raise ConfigError('user ' + usr + ' requires upload speed value') + + if not c['certs']['ca'] or not c['certs']['server-key'] or not c['certs']['server-cert']: + raise ConfigError('service sstp-server sstp-settings ssl-certs needs the ssl certificates set up') + else: + ssl_path = ssl_cert_dir + '/' + if not os.path.exists(ssl_path + c['certs']['ca']): + raise ConfigError('CA {0} doesn\'t exist'.format(ssl_path + c['certs']['ca'])) + if not os.path.exists(ssl_path + c['certs']['server-cert']): + raise ConfigError('SSL Cert {0} doesn\'t exist'.format(ssl_path + c['certs']['server-cert'])) + if not os.path.exists(ssl_path + c['certs']['server-cert']): + raise ConfigError('SSL Key {0} doesn\'t exist'.format(ssl_path + c['certs']['server-key'])) + + if c['authentication']['mode'] == 'radius': + if len(c['authentication']['radius-srv']) == 0: + raise ConfigError('service sstp-server authentication radius-server needs a value') + for rsrv in c['authentication']['radius-srv']: + if c['authentication']['radius-srv'][rsrv]['secret'] == None: + raise ConfigError('service sstp-server authentication radius-server {0} secret requires a value'.format(rsrv)) + + if c['authentication']['mode'] == 'local': + if not c['ip_pool']: + print ("WARNING: service sstp-server network-settings client-ip-settings subnet requires a value") + if not c['gw']: + print ("WARNING: service sstp-server network-settings client-ip-settings gateway-address requires a value") + +def generate(c): + if c == None: + return None + + ### accel-cmd reload doesn't work so any change results in a restart of the daemon + try: + if os.cpu_count() == 1: + c['thread_cnt'] = 1 + else: + c['thread_cnt'] = int(os.cpu_count()/2) + except KeyError: + if os.cpu_count() == 1: + c['thread_cnt'] = 1 + else: + c['thread_cnt'] = int(os.cpu_count()/2) + + tmpl = jinja2.Template(sstp_config, trim_blocks=True) + config_text = tmpl.render(c) + open(sstp_conf,'w').write(config_text) + + if c['authentication']['local-users']: + write_chap_secrets(c) + + return c + +def apply(c): + if c == None: + if os.path.exists(pidfile): + accel_cmd('shutdown hard') + if os.path.exists(pidfile): + os.remove(pidfile) + return None + + if not os.path.exists(pidfile): + ret = subprocess.call(['/usr/sbin/accel-pppd','-c',sstp_conf,'-p',pidfile,'-d']) + chk_con() + if ret !=0 and os.path.exists(pidfile): + os.remove(pidfile) + raise ConfigError('accel-pppd failed to start') + else: + accel_cmd('restart') + sl.syslog(sl.LOG_NOTICE, "reloading config via daemon restart") + +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/bridge_has_members.py b/src/conf_mode/bridge_has_members.py deleted file mode 100755 index 712a9cc46..000000000 --- a/src/conf_mode/bridge_has_members.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (C) 2018 VyOS maintainers and contributors -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License version 2 or later as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. -# -# - -import sys - -import vyos.config - -if len(sys.argv) < 2: - print("Argument (bridge interface name) is required") - sys.exit(1) -else: - bridge = sys.argv[1] - -c = vyos.config.Config() - -members = [] - - -# Check in ethernet and bonding interfaces -for p in ["interfaces ethernet", "interfaces bonding"]: - intfs = c.list_nodes(p) - for i in intfs: - intf_bridge_path = "{0} {1} bridge-group bridge".format(p, i) - if c.exists(intf_bridge_path): - intf_bridge = c.return_value(intf_bridge_path) - if intf_bridge == bridge: - members.append(i) - # Walk VLANs - for v in c.list_nodes("{0} {1} vif".format(p, i)): - vif_bridge_path = "{0} {1} vif {2} bridge-group bridge".format(p, i, v) - if c.exists(vif_bridge_path): - vif_bridge = c.return_value(vif_bridge_path) - if vif_bridge == bridge: - members.append("{0}.{1}".format(i, v)) - # Walk QinQ interfaces - for vs in c.list_nodes("{0} {1} vif-s".format(p, i)): - vifs_bridge_path = "{0} {1} vif-s {2} bridge-group bridge".format(p, i, vs) - if c.exists(vifs_bridge_path): - vifs_bridge = c.return_value(vifs_bridge_path) - if vifs_bridge == bridge: - members.append("{0}.{1}".format(i, vs)) - for vc in c.list_nodes("{0} {1} vif-s {2} vif-c".format(p, i, vs)): - vifc_bridge_path = "{0} {1} vif-s {2} vif-c {3} bridge-group bridge".format(p, i, vs, vc) - if c.exists(vifc_bridge_path): - vifc_bridge = c.return_value(vifc_bridge_path) - if vifc_bridge == bridge: - members.append("{0}.{1}.{2}".format(i, vs, vc)) - -# Check tunnel interfaces -for t in c.list_nodes("interfaces tunnel"): - tunnel_bridge_path = "interfaces tunnel {0} parameters ip bridge-group bridge".format(t) - if c.exists(tunnel_bridge_path): - intf_bridge = c.return_value(tunnel_bridge_path) - if intf_bridge == bridge: - members.append(t) - -# Check OpenVPN interfaces -for o in c.list_nodes("interfaces openvpn"): - ovpn_bridge_path = "interfaces openvpn {0} bridge-group bridge".format(o) - if c.exists(ovpn_bridge_path): - intf_bridge = c.return_value(ovpn_bridge_path) - if intf_bridge == bridge: - members.append(o) - -if members: - print("Bridge {0} cannot be deleted because some interfaces are configured as its members".format(bridge)) - print("The following interfaces are members of {0}: {1}".format(bridge, " ".join(members))) - sys.exit(1) -else: - sys.exit(0) diff --git a/src/conf_mode/dhcpv6_relay.py b/src/conf_mode/dhcpv6_relay.py index 5868abe8a..ccabc901d 100755 --- a/src/conf_mode/dhcpv6_relay.py +++ b/src/conf_mode/dhcpv6_relay.py @@ -52,9 +52,10 @@ def get_config(): if conf.exists('listen-interface'): interfaces = conf.list_nodes('listen-interface') for intf in interfaces: - addr = conf.return_value('listen-interface {0} address'.format(intf)) - listen = addr + '%' + intf - relay['listen_addr'].append(listen) + if conf.exists('listen-interface {0} address'.format(intf)): + addr = conf.return_value('listen-interface {0} address'.format(intf)) + listen = addr + '%' + intf + relay['listen_addr'].append(listen) # Upstream interface/address for remote DHCPv6 server if conf.exists('upstream-interface'): @@ -82,7 +83,7 @@ def verify(relay): return None if len(relay['listen_addr']) == 0 or len(relay['upstream_addr']) == 0: - raise ConfigError('Must set at least one listen and upstream interface.') + raise ConfigError('Must set at least one listen and upstream interface addresses.') return None diff --git a/src/conf_mode/http-api.py b/src/conf_mode/http-api.py index 7d618dded..c1d596ea3 100755 --- a/src/conf_mode/http-api.py +++ b/src/conf_mode/http-api.py @@ -84,15 +84,16 @@ def generate(http_api): def apply(http_api): if http_api is not None: os.system('sudo systemctl restart vyos-http-api.service') - for dep in dependencies: - cmd = '{0}/{1}'.format(vyos_conf_scripts_dir, dep) - try: - subprocess.check_call(cmd, shell=True) - except subprocess.CalledProcessError as err: - raise ConfigError("{}.".format(err)) else: os.system('sudo systemctl stop vyos-http-api.service') + for dep in dependencies: + cmd = '{0}/{1}'.format(vyos_conf_scripts_dir, dep) + try: + subprocess.check_call(cmd, shell=True) + except subprocess.CalledProcessError as err: + raise ConfigError("{}.".format(err)) + if __name__ == '__main__': try: c = get_config() diff --git a/src/conf_mode/https.py b/src/conf_mode/https.py index dae51dd7d..e1e81eef1 100755 --- a/src/conf_mode/https.py +++ b/src/conf_mode/https.py @@ -55,10 +55,13 @@ server { server_name {{ l_addr }}; {% endfor %} - location / { + # proxy settings for HTTP API, if enabled; 503, if not + location ~ /(retrieve|configure) { {% if api %} proxy_pass http://localhost:{{ api.port }}; proxy_buffering off; +{% else %} + return 503; {% endif %} } diff --git a/src/conf_mode/interface-bridge.py b/src/conf_mode/interface-bridge.py new file mode 100755 index 000000000..543349e7b --- /dev/null +++ b/src/conf_mode/interface-bridge.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2019 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 sys +import copy +import subprocess + +import vyos.configinterface as VyIfconfig + +from vyos.config import Config +from vyos import ConfigError + +default_config_data = { + 'address': [], + 'address_remove': [], + 'aging': '300', + 'arp_cache_timeout_ms': '30000', + 'description': '', + 'deleted': False, + 'dhcp_client_id': '', + 'dhcp_hostname': '', + 'dhcpv6_parameters_only': False, + 'dhcpv6_temporary': False, + 'disable': False, + 'disable_link_detect': False, + 'forwarding_delay': '15', + 'hello_time': '2', + 'igmp_querier': 0, + 'intf': '', + 'mac' : '', + 'max_age': '20', + 'member': [], + 'member_remove': [], + 'priority': '32768', + 'stp': 'off' +} + +def subprocess_cmd(command): + process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True) + proc_stdout = process.communicate()[0].strip() + pass + +def diff(first, second): + second = set(second) + return [item for item in first if item not in second] + +def get_config(): + bridge = copy.deepcopy(default_config_data) + conf = Config() + + # determine tagNode instance + try: + bridge['intf'] = os.environ['VYOS_TAGNODE_VALUE'] + except KeyError as E: + print("Interface not specified") + + # Check if bridge has been removed + if not conf.exists('interfaces bridge ' + bridge['intf']): + bridge['deleted'] = True + return bridge + + # set new configuration level + conf.set_level('interfaces bridge ' + bridge['intf']) + + # retrieve configured interface addresses + if conf.exists('address'): + bridge['address'] = conf.return_values('address') + + # retrieve aging - how long addresses are retained + if conf.exists('aging'): + bridge['aging'] = conf.return_value('aging') + + # retrieve interface description + if conf.exists('description'): + bridge['description'] = conf.return_value('description') + + # DHCP client identifier + if conf.exists('dhcp-options client-id'): + bridge['dhcp_client_id'] = conf.return_value('dhcp-options client-id') + + # DHCP client hostname + if conf.exists('dhcp-options host-name'): + bridge['dhcp_hostname'] = conf.return_value('dhcp-options host-name') + + # DHCPv6 acquire only config parameters, no address + if conf.exists('dhcpv6-options parameters-only'): + bridge['dhcpv6_parameters_only'] = True + + # DHCPv6 IPv6 "temporary" address + if conf.exists('dhcpv6-options temporary'): + bridge['dhcpv6_temporary'] = True + + # Disable this bridge interface + if conf.exists('disable'): + bridge['disable'] = True + + # Ignore link state changes + if conf.exists('disable-link-detect'): + bridge['disable_link_detect'] = True + + # Forwarding delay + if conf.exists('forwarding-delay'): + bridge['forwarding_delay'] = conf.return_value('forwarding-delay') + + # Hello packet advertisment interval + if conf.exists('hello-time'): + bridge['hello_time'] = conf.return_value('hello-time') + + # Enable Internet Group Management Protocol (IGMP) querier + if conf.exists('igmp querier'): + bridge['igmp_querier'] = 1 + + # ARP cache entry timeout in seconds + if conf.exists('ip arp-cache-timeout'): + tmp = 1000 * int(conf.return_value('ip arp-cache-timeout')) + bridge['arp_cache_timeout_ms'] = str(tmp) + + # Media Access Control (MAC) address + if conf.exists('mac'): + bridge['mac'] = conf.return_value('mac') + + # Interval at which neighbor bridges are removed + if conf.exists('max-age'): + bridge['max_age'] = conf.return_value('max-age') + + # Determine bridge member interface (currently configured) + for intf in conf.list_nodes('member interface'): + iface = { + 'name': intf, + 'cost': '', + 'priority': '' + } + + if conf.exists('member interface {} cost'.format(intf)): + iface['cost'] = conf.return_value('member interface {} cost'.format(intf)) + + if conf.exists('member interface {} priority'.format(intf)): + iface['priority'] = conf.return_value('member interface {} priority'.format(intf)) + + bridge['member'].append(iface) + + # Determine bridge member interface (currently effective) - to determine which + # interfaces is no longer assigend to the bridge and thus can be removed + eff_intf = conf.list_effective_nodes('member interface') + act_intf = conf.list_nodes('member interface') + bridge['member_remove'] = diff(eff_intf, act_intf) + + # Determine interface addresses (currently effective) - to determine which + # address is no longer valid and needs to be removed from the bridge + eff_addr = conf.return_effective_values('address') + act_addr = conf.return_values('address') + bridge['address_remove'] = diff(eff_addr, act_addr) + + # Priority for this bridge + if conf.exists('priority'): + bridge['priority'] = conf.return_value('priority') + + # Enable spanning tree protocol + if conf.exists('stp'): + bridge['stp'] = 'on' + + return bridge + +def verify(bridge): + if bridge is None: + return None + + conf = Config() + for br in conf.list_nodes('interfaces bridge'): + # it makes no sense to verify ourself in this case + if br == bridge['intf']: + continue + + for intf in bridge['member']: + tmp = conf.list_nodes('interfaces bridge {} member interface'.format(br)) + if intf['name'] in tmp: + raise ConfigError('{} can be assigned to any one bridge only'.format(intf['name'])) + + return None + +def generate(bridge): + if bridge is None: + return None + + return None + +def apply(bridge): + if bridge is None: + return None + + cmd = '' + if bridge['deleted']: + # bridges need to be shutdown first + cmd += 'ip link set dev "{}" down'.format(bridge['intf']) + cmd += ' && ' + # delete bridge + cmd += 'brctl delbr "{}"'.format(bridge['intf']) + subprocess_cmd(cmd) + + else: + # create bridge if it does not exist + if not os.path.exists("/sys/class/net/" + bridge['intf']): + # create bridge interface + cmd += 'brctl addbr "{}"'.format(bridge['intf']) + cmd += ' && ' + # activate "UP" the interface + cmd += 'ip link set dev "{}" up'.format(bridge['intf']) + cmd += ' && ' + + # set ageing time + cmd += 'brctl setageing "{}" "{}"'.format(bridge['intf'], bridge['aging']) + cmd += ' && ' + + # set bridge forward delay + cmd += 'brctl setfd "{}" "{}"'.format(bridge['intf'], bridge['forwarding_delay']) + cmd += ' && ' + + # set hello time + cmd += 'brctl sethello "{}" "{}"'.format(bridge['intf'], bridge['hello_time']) + cmd += ' && ' + + # set max message age + cmd += 'brctl setmaxage "{}" "{}"'.format(bridge['intf'], bridge['max_age']) + cmd += ' && ' + + # set bridge priority + cmd += 'brctl setbridgeprio "{}" "{}"'.format(bridge['intf'], bridge['priority']) + cmd += ' && ' + + # turn stp on/off + cmd += 'brctl stp "{}" "{}"'.format(bridge['intf'], bridge['stp']) + + for intf in bridge['member_remove']: + # remove interface from bridge + cmd += ' && ' + cmd += 'brctl delif "{}" "{}"'.format(bridge['intf'], intf) + + for intf in bridge['member']: + # add interface to bridge + # but only if it is not yet member of this bridge + if not os.path.exists('/sys/devices/virtual/net/' + bridge['intf'] + '/brif/' + intf['name']): + cmd += ' && ' + cmd += 'brctl addif "{}" "{}"'.format(bridge['intf'], intf['name']) + + # set bridge port cost + if intf['cost']: + cmd += ' && ' + cmd += 'brctl setpathcost "{}" "{}" "{}"'.format(bridge['intf'], intf['name'], intf['cost']) + + # set bridge port priority + if intf['priority']: + cmd += ' && ' + cmd += 'brctl setportprio "{}" "{}" "{}"'.format(bridge['intf'], intf['name'], intf['priority']) + + subprocess_cmd(cmd) + + # Change interface MAC address + if bridge['mac']: + VyIfconfig.set_mac_address(bridge['intf'], bridge['mac']) + + # update interface description used e.g. within SNMP + VyIfconfig.set_description(bridge['intf'], bridge['description']) + + # Ignore link state changes? + VyIfconfig.set_link_detect(bridge['intf'], bridge['disable_link_detect']) + + # enable or disable IGMP querier + VyIfconfig.set_multicast_querier(bridge['intf'], bridge['igmp_querier']) + + # ARP cache entry timeout in seconds + VyIfconfig.set_arp_cache_timeout(bridge['intf'], bridge['arp_cache_timeout_ms']) + + # Configure interface address(es) + for addr in bridge['address_remove']: + VyIfconfig.remove_interface_address(bridge['intf'], addr) + + for addr in bridge['address']: + VyIfconfig.add_interface_address(bridge['intf'], addr) + + 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/wireguard.py b/src/conf_mode/interface-wireguard.py index 8234fad0b..8234fad0b 100755 --- a/src/conf_mode/wireguard.py +++ b/src/conf_mode/interface-wireguard.py diff --git a/src/conf_mode/ipsec-settings.py b/src/conf_mode/ipsec-settings.py index 921f20491..8d25e7abd 100755 --- a/src/conf_mode/ipsec-settings.py +++ b/src/conf_mode/ipsec-settings.py @@ -16,16 +16,75 @@ # # +import sys +import re import os import jinja2 +import syslog as sl import vyos.config import vyos.defaults from vyos import ConfigError + +ra_conn_name = "remote-access" charon_conf_file = "/etc/strongswan.d/charon.conf" +ipsec_secrets_flie = "/etc/ipsec.secrets" +ipsec_ra_conn_file = "/etc/ipsec.d/tunnels/"+ra_conn_name +ipsec_conf_flie = "/etc/ipsec.conf" +ca_cert_path = '/etc/ipsec.d/cacerts' +server_cert_path = '/etc/ipsec.d/certs' +server_key_path = '/etc/ipsec.d/private' +delim_ipsec_l2tp_begin = "### VyOS L2TP VPN Begin ###" +delim_ipsec_l2tp_end = "### VyOS L2TP VPN End ###" + +l2pt_ipsec_conf = ''' +{{delim_ipsec_l2tp_begin}} +include {{ipsec_ra_conn_file}} +{{delim_ipsec_l2tp_end}} +''' + +l2pt_ipsec_secrets_conf = ''' +{{delim_ipsec_l2tp_begin}} +{% if ipsec_l2tp_auth_mode == 'pre-shared-secret' %} +{{outside_addr}} %any : PSK "{{ipsec_l2tp_secret}}" +{% elif ipsec_l2tp_auth_mode == 'x509' %} +: RSA {{server_key_file_copied}} +{% endif%} +{{delim_ipsec_l2tp_end}} +''' +l2tp_ipsec_ra_conn_conf = ''' +{{delim_ipsec_l2tp_begin}} +conn {{ra_conn_name}} + type=transport + left={{outside_addr}} + leftsubnet=%dynamic[/1701] + rightsubnet=%dynamic + mark=%unique + auto=add + ike=aes256-sha1-modp1024,3des-sha1-modp1024,3des-sha1-modp1024! + dpddelay=15 + dpdtimeout=45 + dpdaction=clear + esp=aes256-sha1,3des-sha1! + rekey=no +{% if ipsec_l2tp_auth_mode == 'pre-shared-secret' %} + authby=secret + leftauth=psk + rightauth=psk +{% elif ipsec_l2tp_auth_mode == 'x509' %} + authby=rsasig + leftrsasigkey=%cert + rightrsasigkey=%cert + rightca=%same + leftcert={{server_cert_file_copied}} +{% endif %} + ikelifetime={{ipsec_l2tp_ike_lifetime}} + keylife={{ipsec_l2tp_lifetime}} +{{delim_ipsec_l2tp_end}} +''' def get_config(): config = vyos.config.Config() @@ -34,10 +93,133 @@ def get_config(): if config.exists("vpn ipsec options disable-route-autoinstall"): data["install_routes"] = "no" + if config.exists("vpn ipsec ipsec-interfaces interface"): + data["ipsec_interfaces"] = config.return_values("vpn ipsec ipsec-interfaces interface") + + # Init config variables + data["delim_ipsec_l2tp_begin"] = delim_ipsec_l2tp_begin + data["delim_ipsec_l2tp_end"] = delim_ipsec_l2tp_end + data["ipsec_ra_conn_file"] = ipsec_ra_conn_file + data["ra_conn_name"] = ra_conn_name + # Get l2tp ipsec settings + data["ipsec_l2tp"] = False + conf_ipsec_command = "vpn l2tp remote-access ipsec-settings " #last space is useful + if config.exists(conf_ipsec_command): + data["ipsec_l2tp"] = True + + # Authentication params + if config.exists(conf_ipsec_command + "authentication mode"): + data["ipsec_l2tp_auth_mode"] = config.return_value(conf_ipsec_command + "authentication mode") + if config.exists(conf_ipsec_command + "authentication pre-shared-secret"): + data["ipsec_l2tp_secret"] = config.return_value(conf_ipsec_command + "authentication pre-shared-secret") + + # mode x509 + if config.exists(conf_ipsec_command + "authentication x509 ca-cert-file"): + data["ipsec_l2tp_x509_ca_cert_file"] = config.return_value(conf_ipsec_command + "authentication x509 ca-cert-file") + if config.exists(conf_ipsec_command + "authentication x509 crl-file"): + data["ipsec_l2tp_x509_crl_file"] = config.return_value(conf_ipsec_command + "authentication x509 crl-file") + if config.exists(conf_ipsec_command + "authentication x509 server-cert-file"): + data["ipsec_l2tp_x509_server_cert_file"] = config.return_value(conf_ipsec_command + "authentication x509 server-cert-file") + data["server_cert_file_copied"] = server_cert_path+"/"+re.search('\w+(?:\.\w+)*$', config.return_value(conf_ipsec_command + "authentication x509 server-cert-file")).group(0) + if config.exists(conf_ipsec_command + "authentication x509 server-key-file"): + data["ipsec_l2tp_x509_server_key_file"] = config.return_value(conf_ipsec_command + "authentication x509 server-key-file") + data["server_key_file_copied"] = server_key_path+"/"+re.search('\w+(?:\.\w+)*$', config.return_value(conf_ipsec_command + "authentication x509 server-key-file")).group(0) + if config.exists(conf_ipsec_command + "authentication x509 server-key-password"): + data["ipsec_l2tp_x509_server_key_password"] = config.return_value(conf_ipsec_command + "authentication x509 server-key-password") + + # Common l2tp ipsec params + if config.exists(conf_ipsec_command + "ike-lifetime"): + data["ipsec_l2tp_ike_lifetime"] = config.return_value(conf_ipsec_command + "ike-lifetime") + else: + data["ipsec_l2tp_ike_lifetime"] = "3600" + + if config.exists(conf_ipsec_command + "lifetime"): + data["ipsec_l2tp_lifetime"] = config.return_value(conf_ipsec_command + "lifetime") + else: + data["ipsec_l2tp_lifetime"] = "3600" + + if config.exists("vpn l2tp remote-access outside-address"): + data['outside_addr'] = config.return_value('vpn l2tp remote-access outside-address') + return data +### ipsec secret l2tp +def write_ipsec_secrets(c): + tmpl = jinja2.Template(l2pt_ipsec_secrets_conf, trim_blocks=True) + l2pt_ipsec_secrets_txt = tmpl.render(c) + old_umask = os.umask(0o077) + open(ipsec_secrets_flie,'w').write(l2pt_ipsec_secrets_txt) + os.umask(old_umask) + sl.syslog(sl.LOG_NOTICE, ipsec_secrets_flie + ' written') + +### ipsec remote access connection config +def write_ipsec_ra_conn(c): + tmpl = jinja2.Template(l2tp_ipsec_ra_conn_conf, trim_blocks=True) + ipsec_ra_conn_txt = tmpl.render(c) + old_umask = os.umask(0o077) + open(ipsec_ra_conn_file,'w').write(ipsec_ra_conn_txt) + os.umask(old_umask) + sl.syslog(sl.LOG_NOTICE, ipsec_ra_conn_file + ' written') + +### Remove config from file by delimiter +def remove_confs(delim_begin, delim_end, conf_file): + os.system("sed -i '/"+delim_begin+"/,/"+delim_end+"/d' "+conf_file) + + +### Append "include /path/to/ra_conn" to ipsec conf file +def append_ipsec_conf(c): + tmpl = jinja2.Template(l2pt_ipsec_conf, trim_blocks=True) + l2pt_ipsec_conf_txt = tmpl.render(c) + old_umask = os.umask(0o077) + open(ipsec_conf_flie,'a').write(l2pt_ipsec_conf_txt) + os.umask(old_umask) + sl.syslog(sl.LOG_NOTICE, ipsec_conf_flie + ' written') + +### Checking certificate storage and notice if certificate not in /config directory +def check_cert_file_store(cert_name, file_path, dts_path): + if not re.search('^\/config\/.+', file_path): + print("Warning: \"" + file_path + "\" lies outside of /config/auth directory. It will not get preserved during image upgrade.") + #Checking file existence + if not os.path.isfile(file_path): + raise ConfigError("L2TP VPN configuration error: Invalid "+cert_name+" \""+file_path+"\"") + else: + ### Cpy file to /etc/ipsec.d/certs/ /etc/ipsec.d/cacerts/ + # todo make check + ret = os.system('cp -f '+file_path+' '+dts_path) + if ret: + raise ConfigError("L2TP VPN configuration error: Cannot copy "+file_path) + else: + sl.syslog(sl.LOG_NOTICE, file_path + ' copied to '+dts_path) + def verify(data): - pass + # l2tp ipsec check + if data["ipsec_l2tp"]: + # Checking dependecies for "authentication mode pre-shared-secret" + if data.get("ipsec_l2tp_auth_mode") == "pre-shared-secret": + if not data.get("ipsec_l2tp_secret"): + raise ConfigError("pre-shared-secret required") + if not data.get("outside_addr"): + raise ConfigError("outside-address not defined") + + # Checking dependecies for "authentication mode x509" + if data.get("ipsec_l2tp_auth_mode") == "x509": + if not data.get("ipsec_l2tp_x509_server_key_file"): + raise ConfigError("L2TP VPN configuration error: \"server-key-file\" not defined.") + else: + check_cert_file_store("server-key-file", data['ipsec_l2tp_x509_server_key_file'], server_key_path) + + if not data.get("ipsec_l2tp_x509_server_cert_file"): + raise ConfigError("L2TP VPN configuration error: \"server-cert-file\" not defined.") + else: + check_cert_file_store("server-cert-file", data['ipsec_l2tp_x509_server_cert_file'], server_cert_path) + + if not data.get("ipsec_l2tp_x509_ca_cert_file"): + raise ConfigError("L2TP VPN configuration error: \"ca-cert-file\" must be defined for X.509") + else: + check_cert_file_store("ca-cert-file", data['ipsec_l2tp_x509_ca_cert_file'], ca_cert_path) + + if not data.get('ipsec_interfaces'): + raise ConfigError("L2TP VPN configuration error: \"vpn ipsec ipsec-interfaces\" must be specified.") def generate(data): tmpl_path = os.path.join(vyos.defaults.directories["data"], "templates", "ipsec") @@ -51,10 +233,21 @@ def generate(data): with open(charon_conf_file, 'w') as f: f.write(charon_conf) + if data["ipsec_l2tp"]: + remove_confs(delim_ipsec_l2tp_begin, delim_ipsec_l2tp_end, ipsec_conf_flie) + write_ipsec_secrets(data) + write_ipsec_ra_conn(data) + append_ipsec_conf(data) + else: + remove_confs(delim_ipsec_l2tp_begin, delim_ipsec_l2tp_end, ipsec_ra_conn_file) + remove_confs(delim_ipsec_l2tp_begin, delim_ipsec_l2tp_end, ipsec_secrets_flie) + remove_confs(delim_ipsec_l2tp_begin, delim_ipsec_l2tp_end, ipsec_conf_flie) + def apply(data): # Do nothing # StrongSWAN should only be restarted when actual tunnels are configured - pass + # Restart ipsec for l2tp + os.system("ipsec restart >&/dev/null") if __name__ == '__main__': try: diff --git a/src/conf_mode/protocols_bfd.py b/src/conf_mode/protocols_bfd.py index 04549f4b4..98f38035a 100755 --- a/src/conf_mode/protocols_bfd.py +++ b/src/conf_mode/protocols_bfd.py @@ -31,7 +31,7 @@ config_tmpl = """ ! bfd {% for peer in old_peers -%} - no peer {{ peer }} + no peer {{ peer.remote }}{% if peer.multihop %} multihop{% endif %}{% if peer.src_addr %} local-address {{ peer.src_addr }}{% endif %}{% if peer.src_if %} interface {{ peer.src_if }}{% endif %} {% endfor -%} ! {% for peer in new_peers -%} @@ -39,6 +39,8 @@ bfd detect-multiplier {{ peer.multiplier }} receive-interval {{ peer.rx_interval }} transmit-interval {{ peer.tx_interval }} + {% if peer.echo_mode %}echo-mode{% endif %} + {% if peer.echo_interval != '' %}echo-interval {{ peer.echo_interval }}{% endif %} {% if not peer.shutdown %}no {% endif %}shutdown {% endfor -%} ! @@ -49,6 +51,86 @@ default_config_data = { 'old_peers' : [] } +# get configuration for BFD peer from proposed or effective configuration +def get_bfd_peer_config(peer, conf_mode="proposed"): + conf = Config() + conf.set_level('protocols bfd peer {0}'.format(peer)) + + bfd_peer = { + 'remote': peer, + 'shutdown': False, + 'src_if': '', + 'src_addr': '', + 'multiplier': '3', + 'rx_interval': '300', + 'tx_interval': '300', + 'multihop': False, + 'echo_interval': '', + 'echo_mode': False, + } + + # Check if individual peer is disabled + if conf_mode == "effective" and conf.exists_effective('shutdown'): + bfd_peer['shutdown'] = True + if conf_mode == "proposed" and conf.exists('shutdown'): + bfd_peer['shutdown'] = True + + # Check if peer has a local source interface configured + if conf_mode == "effective" and conf.exists_effective('source interface'): + bfd_peer['src_if'] = conf.return_effective_value('source interface') + if conf_mode == "proposed" and conf.exists('source interface'): + bfd_peer['src_if'] = conf.return_value('source interface') + + # Check if peer has a local source address configured - this is mandatory for IPv6 + if conf_mode == "effective" and conf.exists_effective('source address'): + bfd_peer['src_addr'] = conf.return_effective_value('source address') + if conf_mode == "proposed" and conf.exists('source address'): + bfd_peer['src_addr'] = conf.return_value('source address') + + # Tell BFD daemon that we should expect packets with TTL less than 254 + # (because it will take more than one hop) and to listen on the multihop + # port (4784) + if conf_mode == "effective" and conf.exists_effective('multihop'): + bfd_peer['multihop'] = True + if conf_mode == "proposed" and conf.exists('multihop'): + bfd_peer['multihop'] = True + + # Configures the minimum interval that this system is capable of receiving + # control packets. The default value is 300 milliseconds. + if conf_mode == "effective" and conf.exists_effective('interval receive'): + bfd_peer['rx_interval'] = conf.return_effective_value('interval receive') + if conf_mode == "proposed" and conf.exists('interval receive'): + bfd_peer['rx_interval'] = conf.return_value('interval receive') + + # The minimum transmission interval (less jitter) that this system wants + # to use to send BFD control packets. + if conf_mode == "effective" and conf.exists_effective('interval transmit'): + bfd_peer['tx_interval'] = conf.return_effective_value('interval transmit') + if conf_mode == "proposed" and conf.exists('interval transmit'): + bfd_peer['tx_interval'] = conf.return_value('interval transmit') + + # Configures the detection multiplier to determine packet loss. The remote + # transmission interval will be multiplied by this value to determine the + # connection loss detection timer. The default value is 3. + if conf_mode == "effective" and conf.exists_effective('interval multiplier'): + bfd_peer['multiplier'] = conf.return_effective_value('interval multiplier') + if conf_mode == "proposed" and conf.exists('interval multiplier'): + bfd_peer['multiplier'] = conf.return_value('interval multiplier') + + # Configures the minimal echo receive transmission interval that this system is capable of handling + if conf_mode == "effective" and conf.exists_effective('interval echo-interval'): + bfd_peer['echo_interval'] = conf.return_effective_value('interval echo-interval') + if conf_mode == "proposed" and conf.exists('interval echo-interval'): + bfd_peer['echo_interval'] = conf.return_value('interval echo-interval') + + # Enables or disables the echo transmission mode + if conf_mode == "effective" and conf.exists_effective('echo-mode'): + bfd_peer['echo_mode'] = True + if conf_mode == "proposed" and conf.exists('echo-mode'): + bfd_peer['echo_mode'] = True + + return bfd_peer + def get_config(): bfd = copy.deepcopy(default_config_data) conf = Config() @@ -60,56 +142,16 @@ def get_config(): # as we have to use vtysh to talk to FRR we also need to know # which peers are gone due to a config removal - thus we read in # all peers (active or to delete) - bfd['old_peers'] = conf.list_effective_nodes('peer') + for peer in conf.list_effective_nodes('peer'): + bfd['old_peers'].append(get_bfd_peer_config(peer, "effective")) for peer in conf.list_nodes('peer'): - conf.set_level('protocols bfd peer {0}'.format(peer)) - bfd_peer = { - 'remote': peer, - 'shutdown': False, - 'src_if': '', - 'src_addr': '', - 'multiplier': '3', - 'rx_interval': '300', - 'tx_interval': '300', - 'multihop': False - } - - # Check if individual peer is disabled - if conf.exists('shutdown'): - bfd_peer['shutdown'] = True - - # Check if peer has a local source interface configured - if conf.exists('source interface'): - bfd_peer['src_if'] = conf.return_value('source interface') - - # Check if peer has a local source address configured - this is mandatory for IPv6 - if conf.exists('source address'): - bfd_peer['src_addr'] = conf.return_value('source address') - - # Tell BFD daemon that we should expect packets with TTL less than 254 - # (because it will take more than one hop) and to listen on the multihop - # port (4784) - if conf.exists('multihop'): - bfd_peer['multihop'] = True - - # Configures the minimum interval that this system is capable of receiving - # control packets. The default value is 300 milliseconds. - if conf.exists('interval receive'): - bfd_peer['rx_interval'] = conf.return_value('interval receive') - - # The minimum transmission interval (less jitter) that this system wants - # to use to send BFD control packets. - if conf.exists('interval transmit'): - bfd_peer['tx_interval'] = conf.return_value('interval transmit') - - # Configures the detection multiplier to determine packet loss. The remote - # transmission interval will be multiplied by this value to determine the - # connection loss detection timer. The default value is 3. - if conf.exists('interval multiplier'): - bfd_peer['multiplier'] = conf.return_value('interval multiplier') - - bfd['new_peers'].append(bfd_peer) + bfd['new_peers'].append(get_bfd_peer_config(peer)) + + # find deleted peers + set_new_peers = set(conf.list_nodes('peer')) + set_old_peers = set(conf.list_effective_nodes('peer')) + bfd['deleted_peers'] = set_old_peers - set_new_peers return bfd @@ -117,20 +159,39 @@ def verify(bfd): if bfd is None: return None - for peer in bfd['new_peers']: - # Bail out early if peer is shutdown - if peer['shutdown']: - continue + # some variables to use later + conf = Config() + for peer in bfd['new_peers']: # IPv6 peers require an explicit local address/interface combination if vyos.validate.is_ipv6(peer['remote']): if not (peer['src_if'] and peer['src_addr']): - raise ConfigError('BFD IPv6 peers require explicit local address/interface setting') - - # multihop doesn't accept interface names - if peer['multihop'] and peer['src_if']: - raise ConfigError('multihop does not accept interface names') - + raise ConfigError('BFD IPv6 peers require explicit local address and interface setting') + + # multihop require source address + if peer['multihop'] and not peer['src_addr']: + raise ConfigError('Multihop require source address') + + # multihop and echo-mode cannot be used together + if peer['multihop'] and peer['echo_mode']: + raise ConfigError('Multihop and echo-mode cannot be used together') + + # echo interval can be configured only with enabled echo-mode + if peer['echo_interval'] != '' and not peer['echo_mode']: + raise ConfigError('echo-interval can be configured only with enabled echo-mode') + + # check if we deleted peers are not used in configuration + if conf.exists('protocols bgp'): + bgp_as = conf.list_nodes('protocols bgp')[0] + + # check BGP neighbors + for peer in bfd['deleted_peers']: + if conf.exists('protocols bgp {0} neighbor {1} bfd'.format(bgp_as, peer)): + raise ConfigError('Cannot delete BFD peer {0}: it is used in BGP configuration'.format(peer)) + if conf.exists('protocols bgp {0} neighbor {1} peer-group'.format(bgp_as, peer)): + peer_group = conf.return_value('protocols bgp {0} neighbor {1} peer-group'.format(bgp_as, peer)) + if conf.exists('protocols bgp {0} peer-group {1} bfd'.format(bgp_as, peer_group)): + raise ConfigError('Cannot delete BFD peer {0}: it belongs to BGP peer-group {1} with enabled BFD'.format(peer, peer_group)) return None diff --git a/src/migration-scripts/interfaces/0-to-1 b/src/migration-scripts/interfaces/0-to-1 new file mode 100755 index 000000000..38f2bd8f5 --- /dev/null +++ b/src/migration-scripts/interfaces/0-to-1 @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 + +# Change syntax of bridge interface +# - move interface based bridge-group to actual bridge (de-nest) +# - make stp and igmp-snooping nodes valueless +# https://phabricator.vyos.net/T1556 + +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) +base = ['interfaces', 'bridge'] + +if not config.exists(base): + # Nothing to do + sys.exit(0) +else: + # + # make stp and igmp-snooping nodes valueless + # + for br in config.list_nodes(base): + # STP: check if enabled + stp_val = config.return_value(base + [br, 'stp']) + # STP: delete node with old syntax + config.delete(base + [br, 'stp']) + # STP: set new node - if enabled + if stp_val == "true": + config.set(base + [br, 'stp'], value=None) + + # igmp-snooping: check if enabled + igmp_val = config.return_value(base + [br, 'igmp-snooping', 'querier']) + # igmp-snooping: delete node with old syntax + config.delete(base + [br, 'igmp-snooping', 'querier']) + # igmp-snooping: set new node - if enabled + if igmp_val == "enable": + config.set(base + [br, 'igmp', 'querier'], value=None) + + # + # move interface based bridge-group to actual bridge (de-nest) + # + bridge_types = ['bonding', 'ethernet', 'l2tpv3', 'openvpn', 'vxlan', 'wireless'] + for type in bridge_types: + if not config.exists(['interfaces', type]): + continue + + for intf in config.list_nodes(['interfaces', type]): + # check if bridge-group exists + if config.exists(['interfaces', type, intf, 'bridge-group']): + bridge = config.return_value(['interfaces', type, intf, 'bridge-group', 'bridge']) + + # create new bridge member interface + config.set(base + [bridge, 'member', 'interface', intf]) + # format as tag node to avoid loading problems + config.set_tag(base + [bridge, 'member', 'interface']) + + # cost: migrate if configured + if config.exists(['interfaces', type, intf, 'bridge-group', 'cost']): + cost = config.return_value(['interfaces', type, intf, 'bridge-group', 'cost']) + # set new node + config.set(base + [bridge, 'member', 'interface', intf, 'cost'], value=cost) + + if config.exists(['interfaces', type, intf, 'bridge-group', 'priority']): + priority = config.return_value(['interfaces', type, intf, 'bridge-group', 'priority']) + # set new node + config.set(base + [bridge, 'member', 'interface', intf, 'priority'], value=priority) + + # Delete the old bridge-group assigned to an interface + config.delete(['interfaces', type, intf, 'bridge-group']) + + 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/show_vpn_ra.py b/src/op_mode/show_vpn_ra.py new file mode 100755 index 000000000..cf6119c2f --- /dev/null +++ b/src/op_mode/show_vpn_ra.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2019 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 sys +import re +import subprocess +# from subprocess import Popen, PIPE + +# chech connection to pptp and l2tp daemon +def get_sessions(): + absent_pptp = False + absent_l2tp = False + pptp_cmd = ["accel-cmd", "-p 2003", "show sessions"] + l2tp_cmd = ["accel-cmd", "-p 2004", "show sessions"] + err_pattern = "^Connection.+failed$" + # This value for chack only output header without sessions. + len_def_header = 170 + + # Check pptp + ret = subprocess.Popen(pptp_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + (output, err) = ret.communicate() + if not err and len(output.decode("utf-8")) > len_def_header and not re.search(err_pattern, output.decode("utf-8")): + print(output.decode("utf-8")) + else: + absent_pptp = True + + # Check l2tp + ret = subprocess.Popen(l2tp_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + (output, err) = ret.communicate() + if not err and len(output.decode("utf-8")) > len_def_header and not re.search(err_pattern, output.decode("utf-8")): + print(output.decode("utf-8")) + else: + absent_l2tp = True + + if absent_l2tp and absent_pptp: + print("No active remote access VPN sessions") + + +def main(): + get_sessions() + + +if __name__ == '__main__': + main() diff --git a/src/op_mode/snmp_ifmib.py b/src/op_mode/snmp_ifmib.py index 9d56a950b..180892694 100755 --- a/src/op_mode/snmp_ifmib.py +++ b/src/op_mode/snmp_ifmib.py @@ -77,10 +77,16 @@ def show_ifdescr(i): proc = subprocess.Popen(['/usr/bin/lspci', '-mm', '-d', device], stdout=subprocess.PIPE) (out, err) = proc.communicate() + vendor = "" + device = "" + # convert output to string string = out.decode("utf-8").split('"') - vendor = string[3] - device = string[5] + if len(string) >= 3: + vendor = string[3] + + if len(string) >= 5: + device = string[5] ret = 'ifDescr = {0} {1}'.format(vendor, device) return ret.replace('\n', '') diff --git a/src/services/vyos-http-api-server b/src/services/vyos-http-api-server index e11eb6d52..afab9be70 100755 --- a/src/services/vyos-http-api-server +++ b/src/services/vyos-http-api-server @@ -179,6 +179,7 @@ def configure(): @app.route('/retrieve', method='POST') def get_value(): config = app.config['vyos_config'] + session = app.config['vyos_session'] api_keys = app.config['vyos_keys'] @@ -190,8 +191,11 @@ def get_value(): command = bottle.request.forms.get("data") command = json.loads(command) - op = command['op'] - path = " ".join(command['path']) + try: + op = command['op'] + path = " ".join(command['path']) + except KeyError: + return error(400, "Missing required field. \"op\" and \"path\" fields are required") try: if op == 'returnValue': @@ -200,6 +204,12 @@ def get_value(): res = config.return_values(path) elif op == 'exists': res = config.exists(path) + elif op == 'showConfig': + config_format = 'raw' + if 'configFormat' in command: + config_format = command['configFormat'] + + res = session.show_config(command['path'], format=config_format) else: return error(400, "\"{0}\" is not a valid operation".format(op)) except VyOSError as e: diff --git a/src/validators/cidr b/src/validators/cidr deleted file mode 100755 index 815aa8ba1..000000000 --- a/src/validators/cidr +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -ipaddrcheck --is-any-cidr $1 diff --git a/src/validators/file-exists b/src/validators/file-exists new file mode 100755 index 000000000..e179805ed --- /dev/null +++ b/src/validators/file-exists @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2019 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/>. +# +# Description: +# Check if a given file exists on the system. Used for files that +# are referenced from the CLI and need to be preserved during an image upgrade. +# Warn the user if these aren't under /config + +import os +import sys +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument("-d", "--directory", type=str, help="File must be present in this directory.") +parser.add_argument("-e", "--error", action="store_true", help="Tread warnings as errors - change exit code to '1'") +parser.add_argument("file", type=str, help="Path of file to validate") + +args = parser.parse_args() + +msg_prefix = "WARNING: " +if args.error: + msg_prefix = "ERROR: " + +# +# Always check if the given file exists +# +if not os.path.exists(args.file): + print(msg_prefix + "File '{}' not found".format(args.file)) + if args.error: + sys.exit(1) + else: + sys.exit(0) + +# +# Optional check if the file is under a certain directory path +# +if args.directory: + # remove directory path from path to verify + rel_filename = args.file.replace(args.directory, '').lstrip('/') + + if not os.path.exists(args.directory + '/' + rel_filename): + print(msg_prefix + "'{}' lies outside of '{}' directory.\n" \ + "It will not get preserved during image upgrade!".format(args.file, args.directory)) + if args.error: + sys.exit(1) + else: + sys.exit(0) + +sys.exit(0) diff --git a/src/validators/ip-cidr b/src/validators/ip-cidr new file mode 100755 index 000000000..987bf84ca --- /dev/null +++ b/src/validators/ip-cidr @@ -0,0 +1,3 @@ +#!/bin/sh + +ipaddrcheck --is-any-cidr $1 |