Apply and reload managed BIND9 zones

This commit is contained in:
parkel committed 2026-11-19 23:19:25 +01:00
1 parent 4fcbf723de
commit f00eee0f7a
4 files changed
+290 -1

No files matched your search

+9 -1
View File
@@ -141,12 +141,20 @@ def main(argv=None):
commands = parser.add_subparsers(dest="command", required=True)
render = commands.add_parser("render", help="Render a BIND9 zone from a manifest.")
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)
args = parser.parse_args(argv)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
zone = DnsZone.from_manifest(payload)
sys.stdout.write(zone.render())
if args.command == "apply":
from .dns_node_apply import apply_zone
apply_zone(zone)
print(f"Applied BIND9 zone {zone.domain} at SOA serial {zone.serial}.")
else:
sys.stdout.write(zone.render())
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-dns-node: {error}\n")
+151
View File
@@ -0,0 +1,151 @@
import fcntl
import hashlib
import os
import re
import subprocess
import time
from pathlib import Path
from tempfile import TemporaryDirectory
from .dns_node import MAX_SOA_SERIAL
from .node_files import read_root_file, require_root_directory, write_new_file
ZONE_DIRECTORY = Path("/etc/bind/coulobre")
RNDC = ("rndc", "-s", "127.0.0.1")
def apply_zone(zone):
if os.geteuid() != 0:
raise ValueError("Run apply as root on the BIND9 node.")
require_root_directory(ZONE_DIRECTORY, create_mode=0o755)
directory = os.open(ZONE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(directory, fcntl.LOCK_EX)
install_zone(zone, ZONE_DIRECTORY / zone.domain, directory)
finally:
os.close(directory)
def install_zone(zone, path, directory):
domain = zone.domain
config = f'{{ type primary; file "{path}"; allow-update {{ "none"; }}; }};'
registered = check_registration(domain, config)
wanted = zone_file(zone)
previous = read_root_file(path, mode=0o644) if os.path.lexists(path) else None
loaded = None
if registered:
if previous is None:
raise ValueError("The registered zone is missing its managed zone file.")
loaded = active_serial(domain)
if previous is not None:
saved = file_serial(domain, previous)
if (
loaded is not None
and loaded != saved
and not serial_is_newer(saved, loaded)
):
raise ValueError("The loaded SOA serial is ahead of the managed zone file.")
if wanted != previous and (
not serial_is_newer(zone.serial, saved)
or (loaded is not None and not serial_is_newer(zone.serial, loaded))
):
raise ValueError(
"The manifest needs a newer SOA serial than the managed file and loaded zone."
)
if wanted != previous:
install_zone_file(domain, path, wanted)
if registered and loaded == zone.serial:
return
os.fsync(directory)
if registered:
run(*RNDC, "reload", domain)
else:
run(*RNDC, "addzone", domain, config)
wait_for_serial(domain, zone.serial)
def check_registration(domain, config):
missing = (
f"rndc: 'showzone' failed: not found\nno matching zone '{domain}' in any view"
)
shown = run(*RNDC, "showzone", domain, allow_error=missing)
if shown is None:
return False
if " ".join(shown.split()) != f'zone "{domain}" {config}':
raise ValueError(
"BIND9 already has a zone outside Coulobre's managed configuration."
)
return True
def zone_file(zone):
content = zone.render()
header = f"; Coulobre zone {zone.domain} {zone.serial}"
digest = hashlib.sha256(f"{header}\n{content}".encode("utf-8")).hexdigest()
return f"{header} {digest}\n{content}"
def file_serial(domain, zone_text):
header, _, content = zone_text.partition("\n")
metadata, _, checksum = header.rpartition(" ")
matched = re.fullmatch(
rf"; Coulobre zone {re.escape(domain)} ([0-9]{{1,10}})", metadata
)
digest = hashlib.sha256(f"{metadata}\n{content}".encode("utf-8")).hexdigest()
if matched is None or checksum != digest or int(matched[1]) > MAX_SOA_SERIAL:
raise ValueError("The existing zone file is unmanaged or has been modified.")
return int(matched[1])
def serial_is_newer(candidate, previous):
# RFC 1982 compares serials over the forward half of the 32-bit range.
distance = (candidate - previous) % (MAX_SOA_SERIAL + 1)
return 0 < distance < 2**31
def install_zone_file(domain, path, content):
with TemporaryDirectory(dir=path.parent) as scratch:
staged = Path(scratch) / "zone"
write_new_file(staged, content, mode=0o644)
run("named-checkzone", "-i", "local", domain, str(staged))
os.replace(staged, path)
def active_serial(domain):
result = run(*RNDC, "zonestatus", domain)
match = re.search(r"^serial: ([0-9]{1,10})$", result, re.MULTILINE)
if match is None or int(match[1]) > MAX_SOA_SERIAL:
raise ValueError("BIND9 did not report a loaded SOA serial.")
return int(match[1])
def wait_for_serial(domain, serial):
for _ in range(20):
if active_serial(domain) == serial:
return
time.sleep(0.25)
raise ValueError(
f"BIND9 has not loaded SOA serial {serial}. Reapply the manifest to retry."
)
def run(*command, allow_error=None):
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=15,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"},
)
except subprocess.TimeoutExpired:
raise ValueError(f"{command[0]} timed out.") from None
if result.returncode:
details = result.stderr.strip() or result.stdout.strip()
if details == allow_error:
return None
raise ValueError(f"{command[0]} failed ({result.returncode}). {details}")
return result.stdout.strip()
+109
View File
@@ -0,0 +1,109 @@
from dataclasses import replace
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import call, patch
from django.test import SimpleTestCase
from coulobre.dns_node import MAX_SOA_SERIAL, AddressRecord, DnsZone
from coulobre.dns_node_apply import apply_zone, serial_is_newer, zone_file
class DnsZoneApplyTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.zone = DnsZone(
domain="example.net",
serial=1,
nameservers=("ns1.provider.example",),
responsible_name="hostmaster.example.net",
addresses=(AddressRecord("example.net", "192.0.2.20"),),
)
self.updated = replace(
self.zone,
serial=2,
addresses=(AddressRecord("example.net", "192.0.2.21"),),
)
self.path = directory / self.zone.domain
self.registration = (
f'zone "example.net" {{ type primary; file "{self.path}"; '
'allow-update { "none"; }; };'
)
self.commands = self.enterContext(patch("coulobre.dns_node_apply.run"))
self.enterContext(patch("coulobre.dns_node_apply.ZONE_DIRECTORY", directory))
self.enterContext(patch("coulobre.dns_node_apply.require_root_directory"))
self.enterContext(patch("coulobre.dns_node_apply.os.geteuid", return_value=0))
self.enterContext(
patch(
"coulobre.dns_node_apply.read_root_file",
side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"),
)
)
def test_failed_validation_preserves_existing_zone_file_and_registration(self):
self.path.write_text(zone_file(self.zone), encoding="utf-8")
self.commands.side_effect = [
self.registration,
"serial: 1",
ValueError("Zone failed validation."),
]
with self.assertRaisesRegex(ValueError, "failed validation"):
apply_zone(self.updated)
self.assertEqual(self.path.read_text(encoding="utf-8"), zone_file(self.zone))
self.assertEqual(list(self.path.parent.iterdir()), [self.path])
self.assertEqual(self.commands.call_args.args[0], "named-checkzone")
def test_reapplying_after_reload_failure_reuses_the_validated_zone_file(self):
self.path.write_text(zone_file(self.zone), encoding="utf-8")
self.commands.side_effect = [
self.registration,
"serial: 1",
"OK",
ValueError("Reload interrupted."),
]
with self.assertRaisesRegex(ValueError, "Reload interrupted"):
apply_zone(self.updated)
self.assertEqual(self.path.read_text(encoding="utf-8"), zone_file(self.updated))
self.commands.reset_mock()
self.commands.side_effect = [self.registration, "serial: 1", "", "serial: 2"]
apply_zone(self.updated)
self.assertEqual(
self.commands.call_args_list[1:],
[
call("rndc", "-s", "127.0.0.1", "zonestatus", "example.net"),
call("rndc", "-s", "127.0.0.1", "reload", "example.net"),
call("rndc", "-s", "127.0.0.1", "zonestatus", "example.net"),
],
)
def test_unmanaged_running_zone_blocks_installation(self):
self.commands.return_value = (
'zone "example.net" { type primary; file "/etc/bind/existing.example"; };'
)
with self.assertRaisesRegex(ValueError, "outside Coulobre"):
apply_zone(self.zone)
self.assertFalse(self.path.exists())
self.commands.assert_called_once()
def test_modified_zone_file_blocks_replacement(self):
modified = zone_file(self.zone).replace("192.0.2.20", "192.0.2.99")
self.path.write_text(modified, encoding="utf-8")
self.commands.side_effect = [self.registration, "serial: 1"]
with self.assertRaisesRegex(ValueError, "has been modified"):
apply_zone(self.updated)
self.assertEqual(self.path.read_text(encoding="utf-8"), modified)
def test_serial_comparison_wraps_and_rejects_ambiguous_half_range(self):
self.assertTrue(serial_is_newer(0, MAX_SOA_SERIAL))
self.assertFalse(serial_is_newer(MAX_SOA_SERIAL, 0))
self.assertFalse(serial_is_newer(2**31, 0))
self.assertFalse(serial_is_newer(0, 0))