diff --git a/group_vars/all/18_swarm.yml b/group_vars/all/18_swarm.yml index 80b9d85d6b..8b41a6f57d 100644 --- a/group_vars/all/18_swarm.yml +++ b/group_vars/all/18_swarm.yml @@ -20,6 +20,10 @@ STACK_HOST: >- swarm_stack_fatal_grace: 180 +SWARM_INGRESS_GUARDED: "{{ swarm_ingress_endpoints.stdout_lines | swarm_ingress_published | swarm_ingress_guarded(lookup('applications') | swarm_public_ports) }}" + +SWARM_INGRESS_PEERS: "{{ swarm_ingress_nodes.stdout_lines | swarm_node_addresses }}" + swarm: manager: advertise_addr: >- diff --git a/plugins/filter/swarm_ingress_guard.py b/plugins/filter/swarm_ingress_guard.py new file mode 100644 index 0000000000..3786701b34 --- /dev/null +++ b/plugins/filter/swarm_ingress_guard.py @@ -0,0 +1,141 @@ +"""Ports the swarm ingress publishes on every node that no application declares public.""" + +from __future__ import annotations + +import ipaddress +import json +from collections.abc import Iterable, Mapping +from typing import Any + +from ansible.errors import AnsibleFilterError + +_PROTOCOLS = ("tcp", "udp") + + +def swarm_ingress_published(inspect_lines: Iterable[str]) -> list[dict[str, Any]]: + """Return every port the routing mesh publishes, one entry per protocol and port. + + Args: + inspect_lines: one ``docker service inspect --format '{{json .Endpoint.Ports}}'`` + document per service; ``null`` for a service that publishes nothing. + + Returns: + ``{"protocol": "tcp"|"udp", "port": int}`` for each ``ingress`` entry, + sorted and without duplicates; host-mode entries are left out. + + Raises: + AnsibleFilterError: a line is not JSON, or an entry names a protocol + other than tcp or udp. + """ + seen: set[tuple[str, int]] = set() + for line in inspect_lines: + text = str(line).strip() + if not text: + continue + try: + entries = json.loads(text) + except ValueError as exc: + raise AnsibleFilterError( + f"swarm_ingress_published: not JSON: {text!r}" + ) from exc + for entry in entries or []: + if entry.get("PublishMode") != "ingress": + continue + protocol = str(entry.get("Protocol", "")).lower() + if protocol not in _PROTOCOLS: + raise AnsibleFilterError( + f"swarm_ingress_published: unexpected protocol in {entry!r}" + ) + seen.add((protocol, int(entry["PublishedPort"]))) + return [{"protocol": protocol, "port": port} for protocol, port in sorted(seen)] + + +def _expand(value: Any) -> range: + if isinstance(value, Mapping): + return range(int(value["start"]), int(value["end"]) + 1) + return range(int(value), int(value) + 1) + + +def swarm_public_ports(applications: Mapping[str, Any]) -> list[int]: + """Return every port any application declares under ``services.*.ports.public``. + + Args: + applications: the merged ``lookup('applications')`` mapping. + + Returns: + The declared public ports, ``{start, end}`` ranges expanded, sorted and + without duplicates. + """ + ports: set[int] = set() + for application in applications.values(): + services = (application or {}).get("services") or {} + for service in services.values(): + public = (((service or {}).get("ports") or {}).get("public")) or {} + for value in public.values(): + if value in (None, ""): + continue + ports.update(_expand(value)) + return sorted(ports) + + +def swarm_ingress_guarded( + published: Iterable[Mapping[str, Any]], public: Iterable[int] +) -> list[dict[str, Any]]: + """Drop the ports that are public by declaration from the published ones. + + Args: + published: the output of ``swarm_ingress_published``. + public: the output of ``swarm_public_ports``. + + Returns: + The published entries whose port no application declares public. + """ + allowed = set(public) + return [dict(entry) for entry in published if int(entry["port"]) not in allowed] + + +def swarm_node_addresses(inspect_lines: Iterable[str]) -> dict[str, list[str]]: + """Return the addresses the swarm nodes reach each other from, split by family. + + Args: + inspect_lines: one ``docker node inspect --format '{{.Status.Addr}}'`` + line per node. + + Returns: + ``{"ipv4": [...], "ipv6": [...]}``, sorted and without duplicates; the + unspecified address a node may report is left out. + + Raises: + AnsibleFilterError: a line is not an IP address. + """ + families: dict[str, set[ipaddress.IPv4Address | ipaddress.IPv6Address]] = { + "ipv4": set(), + "ipv6": set(), + } + for line in inspect_lines: + text = str(line).strip() + if not text: + continue + try: + address = ipaddress.ip_address(text) + except ValueError as exc: + raise AnsibleFilterError( + f"swarm_node_addresses: not an IP address: {text!r}" + ) from exc + if address.is_unspecified: + continue + families[f"ipv{address.version}"].add(address) + return { + family: [str(address) for address in sorted(addresses)] + for family, addresses in families.items() + } + + +class FilterModule: + def filters(self) -> dict[str, Any]: + return { + "swarm_ingress_published": swarm_ingress_published, + "swarm_public_ports": swarm_public_ports, + "swarm_ingress_guarded": swarm_ingress_guarded, + "swarm_node_addresses": swarm_node_addresses, + } diff --git a/roles/svc-swarm-node/README.md b/roles/svc-swarm-node/README.md index 86923e7cec..6c342481c3 100644 --- a/roles/svc-swarm-node/README.md +++ b/roles/svc-swarm-node/README.md @@ -49,6 +49,11 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( inventory are applied to the joining node. - **Mode-selection trigger:** Membership in `svc-swarm-node` resolves `DEPLOYMENT_MODE = swarm` for every web-app role on that host. +- **Ingress guard:** An nftables table drops packets from outside the cluster + to every routing-mesh port no application declares under `ports.public`. + Loopback, the Docker bridges and the swarm nodes' own addresses stay + admitted. The table is loaded before a node joins and reloaded on every node + after the join and after each stack deploy. ## Quick Setup diff --git a/roles/svc-swarm-node/tasks/00_core.yml b/roles/svc-swarm-node/tasks/00_core.yml index a132a977de..4a878f11d5 100644 --- a/roles/svc-swarm-node/tasks/00_core.yml +++ b/roles/svc-swarm-node/tasks/00_core.yml @@ -4,8 +4,8 @@ - name: "🐝 Swarm-only node setup (cluster bootstrap + shared CA anchor)" when: DEPLOYMENT_MODE == 'swarm' block: - - name: "🥾 Bootstrap docker swarm cluster" - ansible.builtin.include_tasks: 00_core/bootstrap_cluster.yml + - name: "🥾 Join the swarm behind the ingress guard" + ansible.builtin.include_tasks: 00_core/join.yml - name: "✅ Ensure shared Root CA on every swarm node (manager mints, workers fetch)" ansible.builtin.include_role: diff --git a/roles/svc-swarm-node/tasks/00_core/ingress_guard.yml b/roles/svc-swarm-node/tasks/00_core/ingress_guard.yml new file mode 100644 index 0000000000..7daf07e429 --- /dev/null +++ b/roles/svc-swarm-node/tasks/00_core/ingress_guard.yml @@ -0,0 +1,15 @@ +--- +- name: "🔎 Swarm ingress guard | Read the published ports before this node joins" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml') }}" + apply: + run_once: true + delegate_to: "{{ STACK_HOST }}" + +- name: "🛡️ Swarm ingress guard | Bound the non-public published ports" + ansible.builtin.include_role: + name: svc-net-firewall + vars: + FIREWALL_FRAGMENT_ROLE: svc-swarm-node + SWARM_INGRESS_GUARDED_PORTS: "{{ SWARM_INGRESS_GUARDED }}" + SWARM_INGRESS_PEER_ADDRESSES: "{{ SWARM_INGRESS_PEERS }}" diff --git a/roles/svc-swarm-node/tasks/00_core/join.yml b/roles/svc-swarm-node/tasks/00_core/join.yml new file mode 100644 index 0000000000..3133459549 --- /dev/null +++ b/roles/svc-swarm-node/tasks/00_core/join.yml @@ -0,0 +1,9 @@ +--- +- name: "🛡️ Bound the ports the routing mesh publishes before the node joins" + ansible.builtin.include_tasks: 00_core/ingress_guard.yml + +- name: "🥾 Bootstrap docker swarm cluster" + ansible.builtin.include_tasks: 00_core/bootstrap_cluster.yml + +- name: "🛡️ Admit the joined nodes to the bound on every node" + ansible.builtin.include_tasks: utils/ingress_guard/refresh.yml diff --git a/roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml b/roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml new file mode 100644 index 0000000000..052e41d04e --- /dev/null +++ b/roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml @@ -0,0 +1,22 @@ +--- +- name: "🔎 Swarm ingress guard | Read the ports the routing mesh publishes" + ansible.builtin.shell: | + set -euo pipefail + if [ "$(container info --format '{{ '{{.Swarm.ControlAvailable}}' }}')" = "true" ]; then + container service ls -q | xargs -r container service inspect --format '{{ '{{json .Endpoint.Ports}}' }}' + fi + args: + executable: /bin/bash + register: swarm_ingress_endpoints + changed_when: false + +- name: "🔎 Swarm ingress guard | Read the addresses the swarm nodes reach each other from" + ansible.builtin.shell: | + set -euo pipefail + if [ "$(container info --format '{{ '{{.Swarm.ControlAvailable}}' }}')" = "true" ]; then + container node ls -q | xargs -r container node inspect --format '{{ '{{.Status.Addr}}' }}' + fi + args: + executable: /bin/bash + register: swarm_ingress_nodes + changed_when: false diff --git a/roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml b/roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml new file mode 100644 index 0000000000..9f92eb14e9 --- /dev/null +++ b/roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml @@ -0,0 +1,30 @@ +--- +- name: "🔎 Swarm ingress guard | Read the published ports and the swarm nodes" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/svc-swarm-node/tasks/utils/ingress_guard/read.yml') }}" + apply: + run_once: true + delegate_to: "{{ STACK_HOST }}" + +- name: "📄 Swarm ingress guard | Load the fragment naming of svc-net-firewall" + ansible.builtin.include_vars: + file: "{{ lookup('path_absolute', 'roles/svc-net-firewall/vars/main.yml') }}" + name: swarm_ingress_firewall + +- name: "🛡️ Swarm ingress guard | Reload the bound on every swarm node" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/svc-net-firewall/tasks/02_fragment.yml') }}" + apply: + delegate_to: "{{ swarm_ingress_guard_node }}" + vars: + FIREWALL_FRAGMENT_ROLE: svc-swarm-node + FIREWALL_FRAGMENT_DIR: "{{ swarm_ingress_firewall.FIREWALL_FRAGMENT_DIR }}" + FIREWALL_FRAGMENT_SRC: "{{ swarm_ingress_firewall.FIREWALL_FRAGMENT_SRC }}" + FIREWALL_FRAGMENT_FILE: "{{ swarm_ingress_firewall.FIREWALL_FRAGMENT_FILE }}" + FIREWALL_TABLE: "{{ swarm_ingress_firewall.FIREWALL_TABLE }}" + SWARM_INGRESS_GUARDED_PORTS: "{{ SWARM_INGRESS_GUARDED }}" + SWARM_INGRESS_PEER_ADDRESSES: "{{ SWARM_INGRESS_PEERS }}" + loop: "{{ groups['svc-swarm-node'] }}" + loop_control: + loop_var: swarm_ingress_guard_node + run_once: true diff --git a/roles/svc-swarm-node/templates/nftables.conf.j2 b/roles/svc-swarm-node/templates/nftables.conf.j2 new file mode 100644 index 0000000000..1202007ea2 --- /dev/null +++ b/roles/svc-swarm-node/templates/nftables.conf.j2 @@ -0,0 +1,32 @@ +table inet {{ FIREWALL_TABLE }} +delete table inet {{ FIREWALL_TABLE }} +table inet {{ FIREWALL_TABLE }} { +{% for protocol in ['tcp', 'udp'] %} +{% set _ports = SWARM_INGRESS_GUARDED_PORTS | selectattr('protocol', 'equalto', protocol) | map(attribute='port') | list %} + set guarded_{{ protocol }} { + type inet_service +{% if _ports | length > 0 %} + elements = { {{ _ports | join(', ') }} } +{% endif %} + } + +{% endfor %} +{% for family in ['ipv4', 'ipv6'] %} +{% set _addresses = SWARM_INGRESS_PEER_ADDRESSES[family] %} + set peers_{{ family }} { + type {{ family }}_addr +{% if _addresses | length > 0 %} + elements = { {{ _addresses | join(', ') }} } +{% endif %} + } + +{% endfor %} + chain prerouting { + type filter hook prerouting priority -150; policy accept; +{% for family, match in [('ipv4', 'ip'), ('ipv6', 'ip6')] %} +{% for protocol in ['tcp', 'udp'] %} + iifname != { "lo", "docker0", "docker_gwbridge" } iifname != "br-*" {{ match }} saddr != @peers_{{ family }} fib daddr type local {{ protocol }} dport @guarded_{{ protocol }} drop +{% endfor %} +{% endfor %} + } +} diff --git a/roles/sys-svc-compose/handlers/swarm.yml b/roles/sys-svc-compose/handlers/swarm.yml index 20e8e3f08e..02d8cdd6fc 100644 --- a/roles/sys-svc-compose/handlers/swarm.yml +++ b/roles/sys-svc-compose/handlers/swarm.yml @@ -184,6 +184,12 @@ run_once: true delegate_to: "{{ STACK_HOST }}" +- name: "🛡️ swarm: bound the ports the routing mesh now publishes on every node" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-swarm-node/tasks/utils/ingress_guard/refresh.yml') }}" + listen: + - compose-up + - swarm-deploy + - name: "🔄 swarm: force task recreation so in-container state is reloaded" ansible.builtin.shell: | set -euo pipefail diff --git a/tests/unit/python/plugins/filter/test_swarm_ingress_guard.py b/tests/unit/python/plugins/filter/test_swarm_ingress_guard.py new file mode 100644 index 0000000000..f51f3cf3a9 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_swarm_ingress_guard.py @@ -0,0 +1,129 @@ +import ipaddress +import unittest + +from ansible.errors import AnsibleFilterError + +from plugins.filter.swarm_ingress_guard import ( + FilterModule, + swarm_ingress_guarded, + swarm_ingress_published, + swarm_node_addresses, + swarm_public_ports, +) + + +class TestSwarmIngressPublished(unittest.TestCase): + def test_keeps_ingress_entries_only(self): + lines = [ + '[{"Protocol":"tcp","TargetPort":5432,"PublishedPort":5432,"PublishMode":"ingress"}]', + '[{"Protocol":"tcp","TargetPort":80,"PublishedPort":80,"PublishMode":"host"}]', + "null", + ( + '[{"Protocol":"udp","TargetPort":3478,"PublishedPort":3478,"PublishMode":"ingress"},' + '{"Protocol":"tcp","TargetPort":5000,"PublishedPort":30001,"PublishMode":"ingress"}]' + ), + ] + self.assertEqual( + swarm_ingress_published(lines), + [ + {"protocol": "tcp", "port": 5432}, + {"protocol": "tcp", "port": 30001}, + {"protocol": "udp", "port": 3478}, + ], + ) + + def test_a_port_two_services_publish_appears_once(self): + line = '[{"Protocol":"tcp","TargetPort":1,"PublishedPort":8080,"PublishMode":"ingress"}]' + self.assertEqual( + swarm_ingress_published([line, line]), + [{"protocol": "tcp", "port": 8080}], + ) + + def test_no_output_means_no_published_port(self): + self.assertEqual(swarm_ingress_published([]), []) + + def test_refuses_a_line_that_is_not_json(self): + with self.assertRaises(AnsibleFilterError): + swarm_ingress_published(["Error: no such service"]) + + def test_refuses_an_unknown_protocol(self): + line = '[{"Protocol":"sctp","TargetPort":1,"PublishedPort":9,"PublishMode":"ingress"}]' + with self.assertRaises(AnsibleFilterError): + swarm_ingress_published([line]) + + +class TestSwarmPublicPorts(unittest.TestCase): + def test_collects_single_ports_and_expands_ranges(self): + applications = { + "web-app-gitea": { + "services": {"gitea": {"ports": {"public": {"ssh": 2201}}}} + }, + "web-svc-coturn": { + "services": { + "coturn": { + "ports": { + "public": { + "stun_turn": 3478, + "relay": {"start": 49160, "end": 49162}, + } + } + } + } + }, + "web-app-moodle": { + "services": {"moodle": {"ports": {"local": {"http": 8033}}}} + }, + "svc-empty": {"services": None}, + } + self.assertEqual( + swarm_public_ports(applications), + [2201, 3478, 49160, 49161, 49162], + ) + + +class TestSwarmIngressGuarded(unittest.TestCase): + def test_drops_the_ports_declared_public(self): + published = [ + {"protocol": "tcp", "port": 2201}, + {"protocol": "tcp", "port": 5432}, + {"protocol": "udp", "port": 3478}, + {"protocol": "tcp", "port": 30001}, + ] + self.assertEqual( + swarm_ingress_guarded(published, [2201, 3478]), + [{"protocol": "tcp", "port": 5432}, {"protocol": "tcp", "port": 30001}], + ) + + +class TestSwarmNodeAddresses(unittest.TestCase): + def test_splits_by_family_and_drops_the_unspecified_address(self): + unspecified = str(ipaddress.IPv4Address(0)) + lines = ["10.0.0.7", unspecified, "fd00::2", "10.0.0.3", "", "10.0.0.7"] + self.assertEqual( + swarm_node_addresses(lines), + {"ipv4": ["10.0.0.3", "10.0.0.7"], "ipv6": ["fd00::2"]}, + ) + + def test_no_output_means_no_peer(self): + self.assertEqual(swarm_node_addresses([]), {"ipv4": [], "ipv6": []}) + + def test_refuses_a_line_that_is_not_an_address(self): + with self.assertRaises(AnsibleFilterError): + swarm_node_addresses(["Error: This node is not a swarm manager."]) + + +class TestFilterModule(unittest.TestCase): + def test_registers_the_four_filters(self): + self.assertEqual( + set(FilterModule().filters()), + { + "swarm_ingress_published", + "swarm_public_ports", + "swarm_ingress_guarded", + "swarm_node_addresses", + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-firewall/test_fragments.py b/tests/unit/python/roles/svc-net-firewall/test_fragments.py index ecadb860ef..3f3a0aad6d 100644 --- a/tests/unit/python/roles/svc-net-firewall/test_fragments.py +++ b/tests/unit/python/roles/svc-net-firewall/test_fragments.py @@ -31,6 +31,10 @@ from pathlib import Path import jinja2 +from plugins.filter.swarm_ingress_guard import ( + swarm_ingress_published, + swarm_node_addresses, +) from utils.cache.files import iter_project_files, read_text from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_VARS_MAIN @@ -79,6 +83,15 @@ COMMON = { "172.16.0.0/12", "192.168.0.0/16", ], + "SWARM_INGRESS_GUARDED_PORTS": swarm_ingress_published( + [ + ( + '[{"Protocol":"tcp","TargetPort":5432,"PublishedPort":5432,"PublishMode":"ingress"},' + '{"Protocol":"udp","TargetPort":3478,"PublishedPort":3478,"PublishMode":"ingress"}]' + ) + ] + ), + "SWARM_INGRESS_PEER_ADDRESSES": swarm_node_addresses(["10.0.0.2"]), } MODES = ("compose", "swarm")