summaryrefslogtreecommitdiff
path: root/src/etc/dhcp/dhclient-exit-hooks.d/99-ipsec-dhclient-hook
blob: 3f0c9cb7af4483e0ea7d607c776789b7f66342e6 (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
62
63
64
65
66
67
68
69
70
71
72
73
#!/bin/bash
#
# 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/>.

DHCP_HOOK_IFLIST="/tmp/ipsec_dhcp_waiting"

if [ -f $DHCP_HOOK_IFLIST ] && [ "$reason" == "BOUND" ]; then
    if grep -qw $interface $DHCP_HOOK_IFLIST; then
        sudo rm $DHCP_HOOK_IFLIST
        sudo /usr/libexec/vyos/conf_mode/vpn_ipsec.py
        exit 0
    fi
fi

if [ "$reason" == "RENEW" ] || [ "$reason" == "REBIND" ]; then
    if [ "$old_ip_address" == "$new_ip_address" ]; then
        exit 0
    fi
else
    exit 0
fi

python3 - <<PYEND
import os
import re

from vyos.utils.process import call
from vyos.utils.process import cmd
from vyos.utils.file import read_file
from vyos.utils.file import write_file

SWANCTL_CONF="/etc/swanctl/swanctl.conf"

if __name__ == '__main__':
    interface = os.getenv('interface')
    new_ip = os.getenv('new_ip_address')
    old_ip = os.getenv('old_ip_address')

    if os.path.exists(SWANCTL_CONF):
        conf_lines = read_file(SWANCTL_CONF).split("\n")
        found = False
        reset_conns = set()
        to_match = f'# dhcp:{interface}'

        for i, line in enumerate(conf_lines):
            if line.find(to_match) > 0:
                conf_lines[i] = line.replace(old_ip, new_ip)
                found = True
                regex_match = re.search(r'#.* reset:([-_a-zA-Z0-9|@]+)', line)
                if regex_match:
                   connection_name = regex_match[1]
                   reset_conns.add(connection_name)

        if found:
            write_file(SWANCTL_CONF, "\n".join(conf_lines))
            for connection_name in reset_conns:
                call(f'sudo swanctl -t -i {connection_name}')
            call('sudo swanctl -q')

    exit(0)
PYEND