Files
coulobre/src/coulobre/dns_node_apply.py
T

213 lines
6.6 KiB
Python

import fcntl
import hashlib
import os
import re
import subprocess
import time
from pathlib import Path
from tempfile import TemporaryDirectory
from .dns_catalog import sync_member
from .dns_node import MAX_SOA_SERIAL
from .node_files import (
locked_root_directory,
read_root_file,
require_root_directory,
write_new_file,
)
from .node_retirement import RetirementRecord, archive_path
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 = zone_configuration(path)
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:
sync_member(domain, present=True)
return
os.fsync(directory)
if registered:
run(*RNDC, "reload", domain)
else:
run(*RNDC, "addzone", domain, config)
wait_for_serial(domain, zone.serial)
sync_member(domain, present=True)
def zone_configuration(path):
return f'{{ type primary; file "{path}"; allow-update {{ "none"; }}; }};'
def retire_zone(request):
zone = request.resource
with locked_root_directory(ZONE_DIRECTORY):
record = RetirementRecord(ZONE_DIRECTORY, request)
if record.is_complete:
sync_member(zone.domain, present=False)
return
path = ZONE_DIRECTORY / zone.domain
managed = check_registration(zone.domain, zone_configuration(path))
if os.path.lexists(path):
contents = read_root_file(path, mode=0o644)
if contents != zone_file(zone):
raise ValueError("The managed zone changed since the preview.")
elif managed or not record.matches(record.started):
raise ValueError("The managed zone file is missing.")
record.begin()
if managed:
run(*RNDC, "delzone", zone.domain)
if check_registration(zone.domain, zone_configuration(path)):
raise ValueError("BIND9 still has the zone registered.")
archive_path(path, record.directory / "zone")
record.finish()
sync_member(zone.domain, present=False)
def check_registration(domain, config):
missing = (
"rndc: 'showzone' failed: not found\n"
f"no 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()).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()).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()