diff --git a/deploy/systemd/coulobre-dns-apply.socket b/deploy/systemd/coulobre-dns-apply.socket new file mode 100644 index 0000000..c1ab9cc --- /dev/null +++ b/deploy/systemd/coulobre-dns-apply.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre local BIND9 publishing socket + +[Socket] +ListenStream=/run/coulobre-dns-apply.sock +SocketUser=root +SocketGroup=coulobre-dns-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-dns-apply@.service b/deploy/systemd/coulobre-dns-apply@.service new file mode 100644 index 0000000..fc93753 --- /dev/null +++ b/deploy/systemd/coulobre-dns-apply@.service @@ -0,0 +1,20 @@ +[Unit] +Description=Coulobre local BIND9 publishing request +After=named.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +UMask=0022 +ExecStart=/opt/coulobre/bin/coulobre-dns-node apply-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=3min +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +ReadWritePaths=/etc/bind/coulobre diff --git a/docs/development.md b/docs/development.md index e2b6e69..d257c6a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -273,6 +273,28 @@ it again. Coulobre checks the SOA serial, reloads the individual zone, and waits for BIND9 to report the requested serial. Reapply the same manifest to resume after an interrupted reload. See the [BIND9 command reference](https://bind9.readthedocs.io/en/v9.18.39/manpages.html#rndc) and [RFC 1982](https://www.rfc-editor.org/rfc/rfc1982.html). +### Enable local DNS publishing + +On a BIND9 node with the same RNDC setup, install Coulobre in a root-owned +virtual environment at `/opt/coulobre`. Create the managed zone directory and +enable the publishing socket. + +```sh +getent group coulobre-dns-provisioning >/dev/null || sudo groupadd --system coulobre-dns-provisioning +sudo install -d -o root -g root -m 0755 /etc/bind/coulobre +sudo install -m 0644 deploy/systemd/coulobre-dns-apply.socket \ + deploy/systemd/coulobre-dns-apply@.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now coulobre-dns-apply.socket +``` + +Grant the socket group only to the service identity responsible for publishing +zones. Send one version 1 or 2 zone manifest as UTF-8 JSON to +`/run/coulobre-dns-apply.sock`, with a limit of 1 MiB. Shut down the writing +half of the connection and read the JSON reply to EOF. For a valid manifest, +the reply identifies the domain and SOA serial. A `configured` reply means +BIND9 has loaded that serial. A `failed` reply includes a diagnostic. + ## Request a virtual mailbox Open a hosting account and select **Request mailbox**. Enter the part before diff --git a/src/coulobre/dns_node.py b/src/coulobre/dns_node.py index e6a2922..506dc9f 100644 --- a/src/coulobre/dns_node.py +++ b/src/coulobre/dns_node.py @@ -9,12 +9,14 @@ from pathlib import Path import idna from .domain_names import canonical_domain +from .node_requests import serve_apply_request BASE_MANIFEST_VERSION = 1 MAIL_RECORD_MANIFEST_VERSION = 2 MANIFEST_KIND = "bind9_zone" MAX_SOA_SERIAL = 2**32 - 1 TXT_CHUNK_SIZE = 255 +DNS_REQUEST_LIMIT = 1024 * 1024 def dns_name(value): @@ -254,19 +256,27 @@ class DnsZone: txt_records=read_records(data, "txt_records", TxtRecord), ) - def manifest(self): - manifest = { - "version": BASE_MANIFEST_VERSION, + def manifest_identity(self): + version = ( + MAIL_RECORD_MANIFEST_VERSION + if self.mx_records or self.txt_records + else BASE_MANIFEST_VERSION + ) + return { + "version": version, "kind": MANIFEST_KIND, "domain": self.domain, "serial": self.serial, + } + + def manifest(self): + manifest = self.manifest_identity() | { "nameservers": list(self.nameservers), "responsible_name": self.responsible_name, "addresses": [asdict(record) for record in self.addresses], } - if self.mx_records or self.txt_records: + if manifest["version"] == MAIL_RECORD_MANIFEST_VERSION: manifest.update( - version=MAIL_RECORD_MANIFEST_VERSION, mx_records=[asdict(record) for record in self.mx_records], txt_records=[asdict(record) for record in self.txt_records], ) @@ -296,8 +306,23 @@ def main(argv=None): render.add_argument("manifest", type=Path) apply = commands.add_parser("apply", help="Install or update a primary BIND9 zone.") apply.add_argument("manifest", type=Path) + commands.add_parser( + "apply-request", + help="Publish one BIND9 manifest from standard input and report JSON.", + ) args = parser.parse_args(argv) + if args.command == "apply-request": + from .dns_node_apply import apply_zone + + return serve_apply_request( + BASE_MANIFEST_VERSION, + DnsZone.from_manifest, + apply_zone, + limit=DNS_REQUEST_LIMIT, + identity=DnsZone.manifest_identity, + ) + try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) zone = DnsZone.from_manifest(payload) diff --git a/src/coulobre/hosting/test_dns_node.py b/src/coulobre/hosting/test_dns_node.py index 8ee90ff..f7ef92f 100644 --- a/src/coulobre/hosting/test_dns_node.py +++ b/src/coulobre/hosting/test_dns_node.py @@ -1,12 +1,14 @@ import json from contextlib import redirect_stderr, redirect_stdout -from io import StringIO +from io import BytesIO, StringIO from pathlib import Path from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import patch from django.test import SimpleTestCase -from coulobre.dns_node import DnsZone, TxtRecord, main +from coulobre.dns_node import DNS_REQUEST_LIMIT, DnsZone, TxtRecord, main class DnsZoneManifestTests(SimpleTestCase): @@ -170,3 +172,40 @@ class DnsZoneManifestTests(SimpleTestCase): f'{owner}. IN TXT "{"x" * 254}\\195" "\\169\\034\\092\\010"', ) self.assertEqual(TxtRecord(owner, "").render(), f'{owner}. IN TXT ""') + + def test_apply_request_accepts_a_large_zone_and_returns_only_its_identity(self): + manifest = self.manifest | { + "version": 2, + "mx_records": [], + "txt_records": [ + {"name": f"txt{index}.bücher.example", "text": "x" * 256} + for index in range(30) + ], + } + output = self.enterContext(redirect_stdout(StringIO())) + apply = self.enterContext(patch("coulobre.dns_node_apply.apply_zone")) + body = json.dumps(manifest).encode("utf-8") + self.assertGreater(len(body), 4096) + with patch("sys.stdin", SimpleNamespace(buffer=BytesIO(body))): + self.assertEqual(main(["apply-request"]), 0) + apply.assert_called_once_with(DnsZone.from_manifest(manifest)) + self.assertEqual( + json.loads(output.getvalue()), + { + "version": 2, + "kind": "bind9_zone", + "domain": "xn--bcher-kva.example", + "serial": 3, + "state": "configured", + "problem": None, + }, + ) + + def test_apply_request_rejects_oversized_input_before_touching_bind(self): + output = self.enterContext(redirect_stdout(StringIO())) + apply = self.enterContext(patch("coulobre.dns_node_apply.apply_zone")) + body = b" " * (DNS_REQUEST_LIMIT + 1) + with patch("sys.stdin", SimpleNamespace(buffer=BytesIO(body))): + self.assertEqual(main(["apply-request"]), 1) + apply.assert_not_called() + self.assertIn("exceeds", json.loads(output.getvalue())["problem"]) diff --git a/src/coulobre/node_requests.py b/src/coulobre/node_requests.py index 7055796..50803db 100644 --- a/src/coulobre/node_requests.py +++ b/src/coulobre/node_requests.py @@ -4,18 +4,20 @@ import sys MAX_REQUEST_BYTES = 4096 -def serve_apply_request(manifest_version, parse_manifest, apply): +def serve_apply_request( + manifest_version, parse_manifest, apply, *, limit=MAX_REQUEST_BYTES, identity=None +): report = {"version": manifest_version} try: - body = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1) - if len(body) > MAX_REQUEST_BYTES: - raise ValueError(f"The manifest exceeds {MAX_REQUEST_BYTES} bytes.") + body = sys.stdin.buffer.read(limit + 1) + if len(body) > limit: + raise ValueError(f"The manifest exceeds {limit} bytes.") try: payload = json.loads(body.decode("utf-8")) except (ValueError, RecursionError): raise ValueError("Expected a UTF-8 JSON manifest.") from None spec = parse_manifest(payload) - report = spec.manifest() + report = spec.manifest() if identity is None else identity(spec) apply(spec) except (OSError, ValueError) as error: print(json.dumps({**report, "state": "failed", "problem": str(error)}))