Skip to content

Commit

Permalink
Merge pull request #3221 from lucasec/t5873
Browse files Browse the repository at this point in the history
T5873: ipsec remote access VPN: support VTI interfaces.
  • Loading branch information
c-po authored Aug 1, 2024
2 parents b12cd41 + 50cf174 commit 962ead6
Show file tree
Hide file tree
Showing 10 changed files with 687 additions and 55 deletions.
2 changes: 2 additions & 0 deletions data/templates/ipsec/swanctl.conf.j2
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ pools {
{{ pool }} {
{% if pool_config.prefix is vyos_defined %}
addrs = {{ pool_config.prefix }}
{% elif pool_config.range is vyos_defined %}
addrs = {{ pool_config.range.start }}-{{ pool_config.range.stop }}
{% endif %}
{% if pool_config.name_server is vyos_defined %}
dns = {{ pool_config.name_server | join(',') }}
Expand Down
9 changes: 8 additions & 1 deletion data/templates/ipsec/swanctl/remote_access.j2
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
{% endif %}
}
children {
ikev2-vpn {
{{ name }}-client {
esp_proposals = {{ esp | get_esp_ike_cipher(ike) | join(',') }}
{% if esp.life_bytes is vyos_defined %}
life_bytes = {{ esp.life_bytes }}
Expand All @@ -69,6 +69,13 @@
{% set local_port = rw_conf.local.port if rw_conf.local.port is vyos_defined else '' %}
{% set local_suffix = '[%any/{1}]'.format(local_port) if local_port else '' %}
local_ts = {{ local_prefix | join(local_suffix + ",") }}{{ local_suffix }}
{% if rw_conf.bind is vyos_defined %}
{# The key defaults to 0 and will match any policies which similarly do not have a lookup key configuration. #}
{# Thus we simply shift the key by one to also support a vti0 interface #}
{% set if_id = rw_conf.bind | replace('vti', '') | int + 1 %}
if_id_in = {{ if_id }}
if_id_out = {{ if_id }}
{% endif %}
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions interface-definitions/include/ipsec/bind.xml.i
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!-- include start from ipsec/bind.xml.i -->
<leafNode name="bind">
<properties>
<help>VTI tunnel interface associated with this configuration</help>
<completionHelp>
<path>interfaces vti</path>
</completionHelp>
</properties>
</leafNode>
<!-- include end -->
49 changes: 41 additions & 8 deletions interface-definitions/vpn_ipsec.xml.in
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,7 @@
#include <include/dhcp-interface.xml.i>
#include <include/ipsec/local-traffic-selector.xml.i>
#include <include/ipsec/replay-window.xml.i>
#include <include/ipsec/bind.xml.i>
<leafNode name="timeout">
<properties>
<help>Timeout to close connection if no data is transmitted</help>
Expand Down Expand Up @@ -978,6 +979,45 @@
</constraint>
</properties>
</leafNode>
<node name="range">
<properties>
<help>Local IPv4 or IPv6 pool range</help>
</properties>
<children>
<leafNode name="start">
<properties>
<help>First IP address for local pool range</help>
<valueHelp>
<format>ipv4</format>
<description>IPv4 start address of pool</description>
</valueHelp>
<valueHelp>
<format>ipv6</format>
<description>IPv6 start address of pool</description>
</valueHelp>
<constraint>
<validator name="ip-address"/>
</constraint>
</properties>
</leafNode>
<leafNode name="stop">
<properties>
<help>Last IP address for local pool range</help>
<valueHelp>
<format>ipv4</format>
<description>IPv4 end address of pool</description>
</valueHelp>
<valueHelp>
<format>ipv6</format>
<description>IPv6 end address of pool</description>
</valueHelp>
<constraint>
<validator name="ip-address"/>
</constraint>
</properties>
</leafNode>
</children>
</node>
#include <include/name-server-ipv4-ipv6.xml.i>
</children>
</tagNode>
Expand Down Expand Up @@ -1201,14 +1241,7 @@
<help>Virtual tunnel interface</help>
</properties>
<children>
<leafNode name="bind">
<properties>
<help>VTI tunnel interface associated with this configuration</help>
<completionHelp>
<path>interfaces vti</path>
</completionHelp>
</properties>
</leafNode>
#include <include/ipsec/bind.xml.i>
#include <include/ipsec/esp-group.xml.i>
</children>
</node>
Expand Down
19 changes: 17 additions & 2 deletions python/vyos/ifconfig/vti.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from vyos.ifconfig.interface import Interface
from vyos.utils.dict import dict_search
from vyos.utils.vti_updown_db import vti_updown_db_exists, open_vti_updown_db_readonly

@Interface.register
class VTIIf(Interface):
Expand All @@ -27,6 +28,10 @@ class VTIIf(Interface):
},
}

def __init__(self, ifname, **kwargs):
self.bypass_vti_updown_db = kwargs.pop("bypass_vti_updown_db", False)
super().__init__(ifname, **kwargs)

def _create(self):
# This table represents a mapping from VyOS internal config dict to
# arguments used by iproute2. For more information please refer to:
Expand Down Expand Up @@ -57,8 +62,18 @@ def _create(self):
self.set_interface('admin_state', 'down')

def set_admin_state(self, state):
""" Handled outside by /etc/ipsec.d/vti-up-down """
pass
"""
Set interface administrative state to be 'up' or 'down'.
The interface will only be brought 'up' if ith is attached to an
active ipsec site-to-site connection or remote access connection.
"""
if state == 'down' or self.bypass_vti_updown_db:
super().set_admin_state(state)
elif vti_updown_db_exists():
with open_vti_updown_db_readonly() as db:
if db.wantsInterfaceUp(self.ifname):
super().set_admin_state(state)

def get_mac(self):
""" Get a synthetic MAC address. """
Expand Down
194 changes: 194 additions & 0 deletions python/vyos/utils/vti_updown_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
# Copyright 2024 VyOS maintainers and contributors <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.

import os

from contextlib import contextmanager
from syslog import syslog

VTI_WANT_UP_IFLIST = '/tmp/ipsec_vti_interfaces'

def vti_updown_db_exists():
""" Returns true if the database exists """
return os.path.exists(VTI_WANT_UP_IFLIST)

@contextmanager
def open_vti_updown_db_for_create_or_update():
""" Opens the database for reading and writing, creating the database if it does not exist """
if vti_updown_db_exists():
f = open(VTI_WANT_UP_IFLIST, 'r+')
else:
f = open(VTI_WANT_UP_IFLIST, 'x+')
try:
db = VTIUpDownDB(f)
yield db
finally:
f.close()

@contextmanager
def open_vti_updown_db_for_update():
""" Opens the database for reading and writing, returning an error if it does not exist """
f = open(VTI_WANT_UP_IFLIST, 'r+')
try:
db = VTIUpDownDB(f)
yield db
finally:
f.close()

@contextmanager
def open_vti_updown_db_readonly():
""" Opens the database for reading, returning an error if it does not exist """
f = open(VTI_WANT_UP_IFLIST, 'r')
try:
db = VTIUpDownDB(f)
yield db
finally:
f.close()

def remove_vti_updown_db():
""" Brings down any interfaces referenced by the database and removes the database """
# We need to process the DB first to bring down any interfaces still up
with open_vti_updown_db_for_update() as db:
db.removeAllOtherInterfaces([])
# this usage of commit will only ever bring down interfaces,
# do not need to provide a functional interface dict supplier
db.commit(lambda _: None)

os.unlink(VTI_WANT_UP_IFLIST)

class VTIUpDownDB:
# The VTI Up-Down DB is a text-based database of space-separated "ifspecs".
#
# ifspecs can come in one of the two following formats:
#
# persistent format: <interface name>
# indicates the named interface should always be up.
#
# connection format: <interface name>:<connection name>:<protocol>
# indicates the named interface wants to be up due to an established
# connection <connection name> using the <protocol> protocol.
#
# The configuration tree and ipsec daemon connection up-down hook
# modify this file as needed and use it to determine when a
# particular event or configuration change should lead to changing
# the interface state.

def __init__(self, f):
self._fileHandle = f
self._ifspecs = set([entry.strip() for entry in f.read().split(" ") if entry and not entry.isspace()])
self._ifsUp = set()
self._ifsDown = set()

def add(self, interface, connection = None, protocol = None):
"""
Adds a new entry to the DB.
If an interface name, connection name, and protocol are supplied,
creates a connection entry.
If only an interface name is specified, creates a persistent entry
for the given interface.
"""
ifspec = f"{interface}:{connection}:{protocol}" if (connection is not None and protocol is not None) else interface
if ifspec not in self._ifspecs:
self._ifspecs.add(ifspec)
self._ifsUp.add(interface)
self._ifsDown.discard(interface)

def remove(self, interface, connection = None, protocol = None):
"""
Removes a matching entry from the DB.
If no matching entry can be fonud, the operation returns successfully.
"""
ifspec = f"{interface}:{connection}:{protocol}" if (connection is not None and protocol is not None) else interface
if ifspec in self._ifspecs:
self._ifspecs.remove(ifspec)
interface_remains = False
for ifspec in self._ifspecs:
if ifspec.split(':')[0] == interface:
interface_remains = True

if not interface_remains:
self._ifsDown.add(interface)
self._ifsUp.discard(interface)

def wantsInterfaceUp(self, interface):
""" Returns whether the DB contains at least one entry referencing the given interface """
for ifspec in self._ifspecs:
if ifspec.split(':')[0] == interface:
return True

return False

def removeAllOtherInterfaces(self, interface_list):
""" Removes all interfaces not included in the given list from the DB """
updated_ifspecs = set([ifspec for ifspec in self._ifspecs if ifspec.split(':')[0] in interface_list])
removed_ifspecs = self._ifspecs - updated_ifspecs
self._ifspecs = updated_ifspecs
interfaces_to_bring_down = [ifspec.split(':')[0] for ifspec in removed_ifspecs]
self._ifsDown.update(interfaces_to_bring_down)
self._ifsUp.difference_update(interfaces_to_bring_down)

def setPersistentInterfaces(self, interface_list):
""" Updates the set of persistently up interfaces to match the given list """
new_presistent_interfaces = set(interface_list)
current_presistent_interfaces = set([ifspec for ifspec in self._ifspecs if ':' not in ifspec])
added_presistent_interfaces = new_presistent_interfaces - current_presistent_interfaces
removed_presistent_interfaces = current_presistent_interfaces - new_presistent_interfaces

for interface in added_presistent_interfaces:
self.add(interface)

for interface in removed_presistent_interfaces:
self.remove(interface)

def commit(self, interface_dict_supplier):
"""
Writes the DB to disk and brings interfaces up and down as needed.
Only interfaces referenced by entries modified in this DB session
are manipulated. If an interface is called to be brought up, the
provided interface_config_supplier function is invoked and expected
to return the config dictionary for the interface.
"""
from vyos.ifconfig import VTIIf
from vyos.utils.process import call
from vyos.utils.network import get_interface_config

self._fileHandle.seek(0)
self._fileHandle.write(' '.join(self._ifspecs))
self._fileHandle.truncate()

for interface in self._ifsDown:
vti_link = get_interface_config(interface)
vti_link_up = (vti_link['operstate'] != 'DOWN' if 'operstate' in vti_link else False)
if vti_link_up:
call(f'sudo ip link set {interface} down')
syslog(f'Interface {interface} is admin down ...')

self._ifsDown.clear()

for interface in self._ifsUp:
vti_link = get_interface_config(interface)
vti_link_up = (vti_link['operstate'] != 'DOWN' if 'operstate' in vti_link else False)
if not vti_link_up:
vti = interface_dict_supplier(interface)
if 'disable' not in vti:
tmp = VTIIf(interface, bypass_vti_updown_db = True)
tmp.update(vti)
syslog(f'Interface {interface} is admin up ...')

self._ifsUp.clear()
3 changes: 2 additions & 1 deletion smoketest/scripts/cli/test_interfaces_vti.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ def test_add_single_ip_address(self):

self.cli_commit()

# VTI interface are always down and only brought up by IPSec
# VTI interfaces are default down and only brought up when an
# IPSec connection is configured to use them
for intf in self._interfaces:
self.assertTrue(is_intf_addr_assigned(intf, addr))
self.assertEqual(Interface(intf).get_admin_state(), 'down')
Expand Down
Loading

0 comments on commit 962ead6

Please sign in to comment.