From 4fb6cd810b26a8208906631c9f387dc0e9781679 Mon Sep 17 00:00:00 2001 From: Emmanuel Garette Date: Wed, 15 Feb 2023 17:57:25 +0100 Subject: [PATCH] raise if incoming ports are used multiple times --- .../templates/risottofirewall.service | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/seed/host-systemd-machined/templates/risottofirewall.service b/seed/host-systemd-machined/templates/risottofirewall.service index f83aae87..379d21b7 100644 --- a/seed/host-systemd-machined/templates/risottofirewall.service +++ b/seed/host-systemd-machined/templates/risottofirewall.service @@ -1,3 +1,11 @@ +%def %%get_protocol_port(%%port) + %if ':' in %%port + %set %%protocol, %%port = %%port.split(':') + %else + %set %%protocol = 'tcp' + %end if + %return %%protocol, %%port +%end def [Unit] Description=Firewall for Risotto After=network.target @@ -6,22 +14,27 @@ After=network.target Type=oneshot RemainAfterExit=yes %set %%has_rules = False +%set %%incoming_ports = {'tcp': {}, 'udp': {}} %for %%dns in %%machined.machines %set %%machine = %%normalize_family(%%dns) %set %%outgoing = %%machined['machine_' + %%machine]['outgoing_ports_' + %%machine] %if %%outgoing %set %%ip = %%machined['machine_' + %%machine]['ip_' + %%machine] %for %%port in %%outgoing - %if ':' in %%port - %set %%protocol, %%port = %%port.split(':') - %else - %set %%protocol = 'tcp' - %end if + %set %%protocol, %%port = %%get_protocol_port(%%port) ExecStart=/sbin/iptables -t nat -A POSTROUTING -s %%ip -p %%protocol -m %%protocol --dport %%port -o %%output_interface -j MASQUERADE ExecStop=-/sbin/iptables -t nat -D POSTROUTING -s %%ip -p %%protocol -m %%protocol --dport %%port -o %%output_interface -j MASQUERADE %set %%has_rules = False %end for %end if + %set %%incoming = %%machined['machine_' + %%machine]['incoming_ports_' + %%machine] + %for %%port in %%incoming + %set %%protocol, %%port = %%get_protocol_port(%%port) + %if %%port in %%incoming_ports[%%protocol] + %raise Exception('the port "' + %%port + '" cannot be deployed for multiple machines: "' + %%dns + '" and "' + %%incoming_ports[%%protocol][%%port] + '"') + %end if + %set %%incoming_ports[%%protocol][%%port] = %%dns + %end for %end for %if not %%has_rules ExecStart=/usr/bin/echo "No rule"