summaryrefslogtreecommitdiff
path: root/src/etc/ipsec.d/vti-up-down
blob: 2b66dd9e6d76074a4224ded1abeb777b5fa807ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
## Script called up strongswan to bring the vti interface up/down based on the state of the IPSec tunnel.
## Called as vti_up_down vti_intf_name

import os
import sys

from vyos.util import call, get_interface_config, get_interface_address

def get_dhcp_address(interface):
    addr = get_interface_address(interface)
    if not addr:
        return None
    if len(addr['addr_info']) == 0:
        return None
    return addr['addr_info'][0]['local']

if __name__ == '__main__':
    verb = os.getenv('PLUTO_VERB')
    connection = os.getenv('PLUTO_CONNECTION')
    interface = sys.argv[1]
    dhcp_interface = sys.argv[2]

    print(f'vti-up-down: start: {verb} {connection} {interface}')

    if verb in ['up-client', 'up-host']:
        call('sudo ip route delete default table 220')

    vti_link = get_interface_config(interface)

    if not vti_link:
        print('vti-up-down: interface not found')
        sys.exit(0)

    vti_link_up = (vti_link['operstate'] == 'UP' if 'operstate' in vti_link else False)

    if verb in ['up-client', 'up-host']:
        if not vti_link_up:
            if dhcp_interface != 'no':
                local_ip = get_dhcp_address(dhcp_interface)
                call(f'sudo ip tunnel change {interface} local {local_ip}')
            call(f'sudo ip link set {interface} up')
    elif verb in ['down-client', 'down-host']:
        if vti_link_up:
            call(f'sudo ip link set {interface} down')

    print('vti-up-down: finish')