summaryrefslogtreecommitdiff
path: root/src/op_mode
diff options
context:
space:
mode:
Diffstat (limited to 'src/op_mode')
-rwxr-xr-xsrc/op_mode/conntrack_sync.py136
-rwxr-xr-xsrc/op_mode/dynamic_dns.py13
-rwxr-xr-xsrc/op_mode/monitor_bandwidth_test.sh2
-rwxr-xr-xsrc/op_mode/openconnect-control.py2
-rwxr-xr-xsrc/op_mode/show_nat_rules.py6
-rwxr-xr-xsrc/op_mode/vpn_ike_sa.py68
-rwxr-xr-xsrc/op_mode/vpn_ipsec.py206
7 files changed, 423 insertions, 10 deletions
diff --git a/src/op_mode/conntrack_sync.py b/src/op_mode/conntrack_sync.py
new file mode 100755
index 000000000..66ecf8439
--- /dev/null
+++ b/src/op_mode/conntrack_sync.py
@@ -0,0 +1,136 @@
+#!/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/>.
+
+import os
+import syslog
+import xmltodict
+
+from argparse import ArgumentParser
+from vyos.configquery import CliShellApiConfigQuery
+from vyos.util import cmd
+from vyos.util import run
+from vyos.template import render_to_string
+
+conntrackd_bin = '/usr/sbin/conntrackd'
+conntrackd_config = '/run/conntrackd/conntrackd.conf'
+
+parser = ArgumentParser(description='Conntrack Sync')
+group = parser.add_mutually_exclusive_group()
+group.add_argument('--restart', help='Restart connection tracking synchronization service', action='store_true')
+group.add_argument('--reset-cache-internal', help='Reset internal cache', action='store_true')
+group.add_argument('--reset-cache-external', help='Reset external cache', action='store_true')
+group.add_argument('--show-internal', help='Show internal (main) tracking cache', action='store_true')
+group.add_argument('--show-external', help='Show external (main) tracking cache', action='store_true')
+group.add_argument('--show-internal-expect', help='Show internal (expect) tracking cache', action='store_true')
+group.add_argument('--show-external-expect', help='Show external (expect) tracking cache', action='store_true')
+
+def is_configured():
+ """ Check if conntrack-sync service is configured """
+ config = CliShellApiConfigQuery()
+ if not config.exists(['service', 'conntrack-sync']):
+ print('Service conntrackd-sync not configured!')
+ exit(1)
+
+def send_bulk_update():
+ """ send bulk update of internal-cache to other systems """
+ tmp = run(f'{conntrackd_bin} -C {conntrackd_config} -B')
+ if tmp > 0:
+ print('ERROR: failed to send bulk update to other conntrack-sync systems')
+
+def request_sync():
+ """ request resynchronization with other systems """
+ tmp = run(f'{conntrackd_bin} -C {conntrackd_config} -n')
+ if tmp > 0:
+ print('ERROR: failed to request resynchronization of external cache')
+
+def flush_cache(direction):
+ """ flush conntrackd cache (internal or external) """
+ if direction not in ['internal', 'external']:
+ raise ValueError()
+ tmp = run(f'{conntrackd_bin} -C {conntrackd_config} -f {direction}')
+ if tmp > 0:
+ print('ERROR: failed to clear {direction} cache')
+
+def xml_to_stdout(xml):
+ out = []
+ for line in xml.splitlines():
+ if line == '\n':
+ continue
+ parsed = xmltodict.parse(line)
+ out.append(parsed)
+
+ print(render_to_string('conntrackd/conntrackd.op-mode.tmpl', {'data' : out}))
+
+if __name__ == '__main__':
+ args = parser.parse_args()
+ syslog.openlog(ident='conntrack-tools', logoption=syslog.LOG_PID,
+ facility=syslog.LOG_INFO)
+
+ if args.restart:
+ is_configured()
+
+ syslog.syslog('Restarting conntrack sync service...')
+ cmd('systemctl restart conntrackd.service')
+ # request resynchronization with other systems
+ request_sync()
+ # send bulk update of internal-cache to other systems
+ send_bulk_update()
+
+ elif args.reset_cache_external:
+ is_configured()
+ syslog.syslog('Resetting external cache of conntrack sync service...')
+
+ # flush the external cache
+ flush_cache('external')
+ # request resynchronization with other systems
+ request_sync()
+
+ elif args.reset_cache_internal:
+ is_configured()
+ syslog.syslog('Resetting internal cache of conntrack sync service...')
+ # flush the internal cache
+ flush_cache('internal')
+
+ # request resynchronization of internal cache with kernel conntrack table
+ tmp = run(f'{conntrackd_bin} -C {conntrackd_config} -R')
+ if tmp > 0:
+ print('ERROR: failed to resynchronize internal cache with kernel conntrack table')
+
+ # send bulk update of internal-cache to other systems
+ send_bulk_update()
+
+ elif args.show_external or args.show_internal or args.show_external_expect or args.show_internal_expect:
+ is_configured()
+ opt = ''
+ if args.show_external:
+ opt = '-e ct'
+ elif args.show_external_expect:
+ opt = '-e expect'
+ elif args.show_internal:
+ opt = '-i ct'
+ elif args.show_internal_expect:
+ opt = '-i expect'
+
+ if args.show_external or args.show_internal:
+ print('Main Table Entries:')
+ else:
+ print('Expect Table Entries:')
+ out = cmd(f'sudo {conntrackd_bin} -C {conntrackd_config} {opt} -x')
+ xml_to_stdout(out)
+
+ else:
+ parser.print_help()
+ exit(1)
diff --git a/src/op_mode/dynamic_dns.py b/src/op_mode/dynamic_dns.py
index 962943896..263a3b6a5 100755
--- a/src/op_mode/dynamic_dns.py
+++ b/src/op_mode/dynamic_dns.py
@@ -36,6 +36,10 @@ update-status: {{ entry.status }}
"""
def show_status():
+ # A ddclient status file must not always exist
+ if not os.path.exists(cache_file):
+ sys.exit(0)
+
data = {
'hosts': []
}
@@ -61,11 +65,10 @@ def show_status():
if ip:
outp['ip'] = ip.split(',')[0]
- if 'atime=' in line:
- atime = line.split('atime=')[1]
- if atime:
- tmp = atime.split(',')[0]
- outp['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(int(tmp, base=10)))
+ if 'mtime=' in line:
+ mtime = line.split('mtime=')[1]
+ if mtime:
+ outp['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(int(mtime.split(',')[0], base=10)))
if 'status=' in line:
status = line.split('status=')[1]
diff --git a/src/op_mode/monitor_bandwidth_test.sh b/src/op_mode/monitor_bandwidth_test.sh
index 6da0291c5..900223bca 100755
--- a/src/op_mode/monitor_bandwidth_test.sh
+++ b/src/op_mode/monitor_bandwidth_test.sh
@@ -26,5 +26,5 @@ elif [[ $(dig $1 AAAA +short | grep -v '\.$' | wc -l) -gt 0 ]]; then
OPT="-V"
fi
-/usr/bin/iperf $OPT -c $1
+/usr/bin/iperf $OPT -c $1 $2
diff --git a/src/op_mode/openconnect-control.py b/src/op_mode/openconnect-control.py
index ef9fe618c..c3cd25186 100755
--- a/src/op_mode/openconnect-control.py
+++ b/src/op_mode/openconnect-control.py
@@ -58,7 +58,7 @@ def main():
is_ocserv_configured()
if args.action == "restart":
- run("systemctl restart ocserv")
+ run("sudo systemctl restart ocserv.service")
sys.exit(0)
elif args.action == "show_sessions":
show_sessions()
diff --git a/src/op_mode/show_nat_rules.py b/src/op_mode/show_nat_rules.py
index 68cff61c8..4b7e40d1f 100755
--- a/src/op_mode/show_nat_rules.py
+++ b/src/op_mode/show_nat_rules.py
@@ -34,8 +34,8 @@ if args.source or args.destination:
tmp = json.loads(tmp)
format_nat66_rule = '{0: <10} {1: <50} {2: <50} {3: <10}'
- print(format_nat66_rule.format("Rule", "Source" if args.source else "Destination", "Translation", "Outbound Interface" if args.source else "Inbound Interface"))
- print(format_nat66_rule.format("----", "------" if args.source else "-----------", "-----------", "------------------" if args.source else "-----------------"))
+ print(format_nat_rule.format("Rule", "Source" if args.source else "Destination", "Translation", "Outbound Interface" if args.source else "Inbound Interface"))
+ print(format_nat_rule.format("----", "------" if args.source else "-----------", "-----------", "------------------" if args.source else "-----------------"))
data_json = jmespath.search('nftables[?rule].rule[?chain]', tmp)
for idx in range(0, len(data_json)):
@@ -86,7 +86,7 @@ if args.source or args.destination:
else:
tran_addr = dict_search('snat.addr' if args.source else 'dnat.addr', data['expr'][3])
- print(format_nat66_rule.format(rule, srcdest, tran_addr, interface))
+ print(format_nat_rule.format(rule, srcdest, tran_addr, interface))
exit(0)
else:
diff --git a/src/op_mode/vpn_ike_sa.py b/src/op_mode/vpn_ike_sa.py
new file mode 100755
index 000000000..28da9f8dc
--- /dev/null
+++ b/src/op_mode/vpn_ike_sa.py
@@ -0,0 +1,68 @@
+#!/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/>.
+
+import argparse
+import re
+import vici
+
+ike_sa_peer_prefix = """\
+Peer ID / IP Local ID / IP
+------------ -------------"""
+
+ike_sa_tunnel_prefix = """
+
+ State IKEVer Encrypt Hash D-H Group NAT-T A-Time L-Time
+ ----- ------ ------- ---- --------- ----- ------ ------"""
+
+def s(byte_string):
+ return str(byte_string, 'utf-8')
+
+def ike_sa(peer, nat):
+ session = vici.Session()
+ sas = session.list_sas()
+ peers = []
+ for conn in sas:
+ for name, sa in conn.items():
+ if peer and not name.startswith('peer-' + peer):
+ continue
+ if name.startswith('peer-') and name in peers:
+ continue
+ if nat and 'nat-local' not in sa:
+ continue
+ peers.append(name)
+ remote_str = f'{s(sa["remote-host"])} {s(sa["remote-id"])}' if s(sa['remote-id']) != '%any' else s(sa["remote-host"])
+ local_str = f'{s(sa["local-host"])} {s(sa["local-id"])}' if s(sa['local-id']) != '%any' else s(sa["local-host"])
+ print(ike_sa_peer_prefix)
+ print('%-39s %-39s' % (remote_str, local_str))
+ state = 'up' if 'state' in sa and s(sa['state']) == 'ESTABLISHED' else 'down'
+ version = 'IKEv' + s(sa['version'])
+ encryption = f'{s(sa["encr-alg"])}_{s(sa["encr-keysize"])}' if 'encr-alg' in sa else 'n/a'
+ integrity = s(sa['integ-alg']) if 'integ-alg' in sa else 'n/a'
+ dh_group = s(sa['dh-group']) if 'dh-group' in sa else 'n/a'
+ natt = 'yes' if 'nat-local' in sa and s(sa['nat-local']) == 'yes' else 'no'
+ atime = s(sa['established']) if 'established' in sa else '0'
+ ltime = s(sa['rekey-time']) if 'rekey_time' in sa else '0'
+ print(ike_sa_tunnel_prefix)
+ print(' %-6s %-6s %-12s %-13s %-14s %-6s %-7s %-7s\n' % (state, version, encryption, integrity, dh_group, natt, atime, ltime))
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--peer', help='Peer name', required=False)
+ parser.add_argument('--nat', help='NAT Traversal', required=False)
+
+ args = parser.parse_args()
+
+ ike_sa(args.peer, args.nat) \ No newline at end of file
diff --git a/src/op_mode/vpn_ipsec.py b/src/op_mode/vpn_ipsec.py
new file mode 100755
index 000000000..434186abb
--- /dev/null
+++ b/src/op_mode/vpn_ipsec.py
@@ -0,0 +1,206 @@
+#!/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/>.
+
+import base64
+import os
+import re
+import struct
+import sys
+import argparse
+from subprocess import TimeoutExpired
+
+from vyos.util import ask_yes_no, call, cmd, process_named_running
+from Crypto.PublicKey.RSA import importKey
+
+RSA_LOCAL_KEY_PATH = '/config/ipsec.d/rsa-keys/localhost.key'
+RSA_LOCAL_PUB_PATH = '/etc/ipsec.d/certs/localhost.pub'
+RSA_KEY_PATHS = ['/config/auth', '/config/ipsec.d/rsa-keys']
+
+X509_CONFIG_PATH = '/etc/ipsec.d/key-pair.template'
+X509_PATH = '/config/auth/'
+
+IPSEC_CONF = '/etc/ipsec.conf'
+SWANCTL_CONF = '/etc/swanctl.conf'
+
+def migrate_to_vyatta_key(path):
+ with open(path, 'r') as f:
+ key = importKey(f.read())
+ e = key.e.to_bytes((key.e.bit_length() + 7) // 8, 'big')
+ n = key.n.to_bytes((key.n.bit_length() + 7) // 8, 'big')
+ return '0s' + str(base64.b64encode(struct.pack('B', len(e)) + e + n), 'ascii')
+ return None
+
+def find_rsa_keys():
+ keys = []
+ for path in RSA_KEY_PATHS:
+ if not os.path.exists(path):
+ continue
+ for filename in os.listdir(path):
+ full_path = os.path.join(path, filename)
+ if os.path.isfile(full_path) and full_path.endswith(".key"):
+ keys.append(full_path)
+ return keys
+
+def show_rsa_keys():
+ for key_path in find_rsa_keys():
+ print('Private key: ' + os.path.basename(key_path))
+ print('Public key: ' + migrate_to_vyatta_key(key_path) + '\n')
+
+def generate_rsa_key(bits = 2192):
+ if (bits < 16 or bits > 4096) or bits % 16 != 0:
+ print('Invalid bit length')
+ return
+
+ if os.path.exists(RSA_LOCAL_KEY_PATH):
+ if not ask_yes_no("A local RSA key file already exists and will be overwritten. Continue?"):
+ return
+
+ print(f'Generating rsa-key to {RSA_LOCAL_KEY_PATH}')
+
+ directory = os.path.dirname(RSA_LOCAL_KEY_PATH)
+ call(f'sudo mkdir -p {directory}')
+ result = call(f'sudo /usr/bin/openssl genrsa -out {RSA_LOCAL_KEY_PATH} {bits}')
+
+ if result != 0:
+ print(f'Could not generate RSA key: {result}')
+ return
+
+ call(f'sudo /usr/bin/openssl rsa -inform PEM -in {RSA_LOCAL_KEY_PATH} -pubout -out {RSA_LOCAL_PUB_PATH}')
+
+ print('Your new local RSA key has been generated')
+ print('The public portion of the key is:\n')
+ print(migrate_to_vyatta_key(RSA_LOCAL_KEY_PATH))
+
+def generate_x509_pair(name):
+ if os.path.exists(X509_PATH + name):
+ if not ask_yes_no("A certificate request with this name already exists and will be overwritten. Continue?"):
+ return
+
+ result = os.system(f'openssl req -new -nodes -keyout {X509_PATH}{name}.key -out {X509_PATH}{name}.csr -config {X509_CONFIG_PATH}')
+
+ if result != 0:
+ print(f'Could not generate x509 key-pair: {result}')
+ return
+
+ print('Private key and certificate request has been generated')
+ print(f'CSR: {X509_PATH}{name}.csr')
+ print(f'Private key: {X509_PATH}{name}.key')
+
+def get_peer_connections(peer, tunnel, return_all = False):
+ search = rf'^conn (peer-{peer}-(tunnel-[\d]+|vti))$'
+ matches = []
+ with open(IPSEC_CONF, 'r') as f:
+ for line in f.readlines():
+ result = re.match(search, line)
+ if result:
+ suffix = f'tunnel-{tunnel}' if tunnel.isnumeric() else tunnel
+ if return_all or (result[2] == suffix):
+ matches.append(result[1])
+ return matches
+
+def reset_peer(peer, tunnel):
+ if not peer:
+ print('Invalid peer, aborting')
+ return
+
+ conns = get_peer_connections(peer, tunnel, return_all = (not tunnel or tunnel == 'all'))
+
+ if not conns:
+ print('Tunnel(s) not found, aborting')
+ return
+
+ result = True
+ for conn in conns:
+ try:
+ call(f'sudo /usr/sbin/ipsec down {conn}', timeout = 10)
+ call(f'sudo /usr/sbin/ipsec up {conn}', timeout = 10)
+ except TimeoutExpired as e:
+ print(f'Timed out while resetting {conn}')
+ result = False
+
+
+ print('Peer reset result: ' + ('success' if result else 'failed'))
+
+def get_profile_connection(profile, tunnel = None):
+ search = rf'(dmvpn-{profile}-[\w]+)' if tunnel == 'all' else rf'(dmvpn-{profile}-{tunnel})'
+ with open(SWANCTL_CONF, 'r') as f:
+ for line in f.readlines():
+ result = re.search(search, line)
+ if result:
+ return result[1]
+ return None
+
+def reset_profile(profile, tunnel):
+ if not profile:
+ print('Invalid profile, aborting')
+ return
+
+ if not tunnel:
+ print('Invalid tunnel, aborting')
+ return
+
+ conn = get_profile_connection(profile)
+
+ if not conn:
+ print('Profile not found, aborting')
+ return
+
+ call(f'sudo /usr/sbin/ipsec down {conn}')
+ result = call(f'sudo /usr/sbin/ipsec up {conn}')
+
+ print('Profile reset result: ' + ('success' if result == 0 else 'failed'))
+
+def debug_peer(peer, tunnel):
+ if not peer or peer == "all":
+ call('sudo /usr/sbin/ipsec statusall')
+ return
+
+ if not tunnel or tunnel == 'all':
+ tunnel = ''
+
+ conn = get_peer_connection(peer, tunnel)
+
+ if not conn:
+ print('Peer not found, aborting')
+ return
+
+ call(f'sudo /usr/sbin/ipsec statusall | grep {conn}')
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--action', help='Control action', required=True)
+ parser.add_argument('--bits', help='Bits for rsa-key', required=False)
+ parser.add_argument('--name', help='Name for x509 key-pair, peer for reset', required=False)
+ parser.add_argument('--tunnel', help='Specific tunnel of peer', required=False)
+
+ args = parser.parse_args()
+
+ if args.action == 'rsa-key':
+ bits = int(args.bits) if args.bits else 2192
+ generate_rsa_key(bits)
+ elif args.action == 'rsa-key-show':
+ show_rsa_keys()
+ elif args.action == 'x509':
+ if not args.name:
+ print('Invalid name for key-pair, aborting.')
+ sys.exit(0)
+ generate_x509_pair(args.name)
+ elif args.action == 'reset-peer':
+ reset_peer(args.name, args.tunnel)
+ elif args.action == "reset-profile":
+ reset_profile(args.name, args.tunnel)
+ elif args.action == "vpn-debug":
+ debug_peer(args.name, args.tunnel)