"""The server's authoritative name server, PowerDNS with its gpgsql backend, for linux-manager-setup and the web service. The name server is the primary of its domains and answers on the addresses of the interfaces of dns.listen. The domains and the records an administrator added (manual records) are in the linux-manager-dns database, which provision() creates with its role and the password in DATABASE_SECRET, and fills with the schema of pdns-backend-pgsql, PDNS_SCHEMA; DNS_SQL defines the server's own tables and procedures, and the first connection of a process loads it. apply() writes every domain as a primary zone: its SOA with wan.local_fqdn as the primary name server, its NS, wan.local_fqdn and dns.secondary, the NS of the domains directly below it, an A or AAAA record for every host name of an enabled site with dns router whose closest domain it is, with the server's address the site chooses, and the manual records, but those of a name and type the records before them have. wan.local_fqdn gets no record in the zones: its record is kept where its own domain is. The addresses dns.secondary resolves to are notified of every change (ALSO-NOTIFY) and may transfer the zones (ALLOW-AXFR-FROM); the serial of the SOA grows only when the records change. Every failure of the database raises DatabaseError; a request that cannot be done raises Failure. """ import contextlib import ipaddress import pathlib import re import socket import psycopg from psycopg.rows import dict_row import linuxmanager import linuxmanager_auth DATABASE = 'linux-manager-dns' DATABASE_SECRET = pathlib.Path('/etc/linux-manager/dns-database.secret') DNS_SQL = pathlib.Path('/usr/share/linux-manager/sql/dns.sql') #: The schema of PowerDNS's gpgsql backend, which pdns-backend-pgsql installs. PDNS_SCHEMA = pathlib.Path('/usr/share/pdns-backend-pgsql/schema/schema.pgsql.sql') #: The settings of PowerDNS that linux-manager-setup writes, read after /etc/powerdns/pdns.conf; the server, its unit and #: the group it runs as. PDNS_CONF = pathlib.Path('/etc/powerdns/pdns.d/linux-manager.conf') PDNS_SERVER = pathlib.Path('/usr/sbin/pdns_server') UNIT = 'pdns.service' GROUP = 'pdns' #: The types of the manual records. TYPES = ('A', 'AAAA', 'CNAME', 'TXT', 'MX', 'SRV', 'CAA') #: The most domains, and manual records of a domain. DOMAINS_MAX = 100 MANUAL_MAX = 1000 #: The refresh, retry and expire times of the SOA, in seconds. SOA_TIMES = '10800 3600 604800' #: A label of a record's name: letters, digits, hyphens and underscores, or * as the first label. LABEL = re.compile(r'^[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?$') #: The content of an MX, SRV and CAA record, and a DNS name a record points to. MX = re.compile(r'^(\d{1,5}) (\S+)$') SRV = re.compile(r'^(\d{1,5}) (\d{1,5}) (\d{1,5}) (\S+)$') CAA = re.compile(r'^(0|128) (issue|issuewild|iodef) "[^"\\]*"$') TARGET = re.compile(r'^[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?(\.[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?)*$') #: The longest content of a TXT record, in characters. TXT_MAX = 2048 #: Whether this process has loaded DNS_SQL. _loaded = False class DatabaseError(Exception): """The database of the name server failed.""" class Failure(Exception): """A request that cannot be done; status is 2 invalid, 3 no such domain or record, 4 the domain exists.""" def __init__(self, message, status=2): super().__init__(message) self.status = status def provision(): """Create the role, its password file and the database of the name server when they are missing, and PowerDNS's tables in it; DatabaseError while pdns-backend-pgsql is not installed.""" linuxmanager_auth.provision_database(DATABASE, DATABASE_SECRET) try: with psycopg.connect(linuxmanager_auth.local_connection(DATABASE, DATABASE_SECRET), autocommit=True) as connection: if connection.execute("SELECT to_regclass('public.domains')").fetchone()[0] is None: connection.execute(PDNS_SCHEMA.read_text(encoding='utf-8')) except OSError as exc: raise DatabaseError(f'the schema of PowerDNS cannot be read: {exc}') from exc except psycopg.Error as exc: raise DatabaseError(f'the database of the name server failed: {exc}') from exc @contextlib.contextmanager def database(): """A connection to the database of the name server, with the server's tables and procedures, closed at the end; DatabaseError on any failure, also before provision() made it.""" global _loaded try: schema = None if _loaded else DNS_SQL.read_text(encoding='utf-8') target = linuxmanager_auth.local_connection(DATABASE, DATABASE_SECRET) except OSError as exc: raise DatabaseError(f'the database of the name server is not ready: {exc}') from exc try: with psycopg.connect(target, autocommit=True, row_factory=dict_row) as connection: if schema is not None: connection.execute(schema) _loaded = True yield connection except psycopg.Error as exc: raise DatabaseError(f'the database of the name server failed: {exc}') from exc def in_zone(zone, name): return name == zone or name.endswith(f'.{zone}') def absolute(zone, name): """The record name in the zone: @ or '' is the zone itself, a name ending in a dot is taken as it is, any other is relative to the zone; Failure for a name outside the zone or not a DNS name.""" if not isinstance(name, str): raise Failure('name must be a string') name = name.strip().lower() if name in ('', '@'): return zone full = name[:-1] if name.endswith('.') else f'{name}.{zone}' labels = full.split('.') if not in_zone(zone, full) or not all(LABEL.match(label) or (index == 0 and label == '*') for index, label in enumerate(labels)): raise Failure(f'{name!r} is not a name in {zone}') return full def check_record(zone, record): """The manual record {name, type, content, ttl?} with its name made absolute and its content checked; Failure when it is not valid. A TXT content not in quotes is quoted.""" if not isinstance(record, dict): raise Failure('a record is an object of name, type, content and ttl') name = absolute(zone, record.get('name')) kind = record.get('type') content = record.get('content') ttl = record.get('ttl') if kind not in TYPES: raise Failure(f'type must be one of {", ".join(TYPES)}') if not isinstance(content, str) or not content.strip(): raise Failure('content must be a string') if ttl is not None and (isinstance(ttl, bool) or not isinstance(ttl, int) or not 60 <= ttl <= 86400): raise Failure('ttl must be 60 to 86400 seconds') content = content.strip() if kind in ('A', 'AAAA'): try: address = ipaddress.ip_address(content) except ValueError: address = None if address is None or address.version != (4 if kind == 'A' else 6): raise Failure(f'{content!r} is not an IPv{4 if kind == "A" else 6} address') content = str(address) elif kind == 'CNAME': if name == zone: raise Failure('the zone itself cannot have a CNAME record') content = content.lower().rstrip('.') if not TARGET.match(content): raise Failure(f'{content!r} is not a DNS name') elif kind == 'TXT': if not (content.startswith('"') and content.endswith('"') and len(content) > 1): content = '"' + content.replace('\\', '\\\\').replace('"', '\\"') + '"' if len(content) > TXT_MAX or not content.isprintable(): raise Failure(f'the text must have at most {TXT_MAX} printable characters') elif kind in ('MX', 'SRV'): match = (MX if kind == 'MX' else SRV).match(content.lower()) if not match or any(int(value) > 65535 for value in match.groups()[:-1]) or \ not TARGET.match(match.groups()[-1].rstrip('.')): raise Failure(f'{kind} content is ' + ('" "' if kind == 'MX' else '" "')) content = ' '.join([*match.groups()[:-1], match.groups()[-1].rstrip('.')]) elif not CAA.match(content): raise Failure('CAA content is "<0 or 128> \\"\\""') return {'name': name, 'type': kind, 'content': content, 'ttl': ttl} def closest(zones, name): """The longest of the zones the name is in, None when it is in none.""" return max((zone for zone in zones if in_zone(zone, name)), key=len, default=None) def check_domain(name): """The domain name in lowercase without a final dot; Failure when it is not a DNS name.""" if not isinstance(name, str) or not linuxmanager.ZONE_NAME.match(name.strip().lower().rstrip('.')): raise Failure(f'{name!r} is not a domain name') return name.strip().lower().rstrip('.') def check_ttl(ttl): if ttl is not None and (isinstance(ttl, bool) or not isinstance(ttl, int) or not linuxmanager.DNS_TTL_RANGE[0] <= ttl <= linuxmanager.DNS_TTL_RANGE[1]): raise Failure(f'ttl must be {linuxmanager.DNS_TTL_RANGE[0]} to {linuxmanager.DNS_TTL_RANGE[1]} seconds') return ttl def domain(connection, name): """The domain; Failure with status 3 when there is none.""" row = next((row for row in connection.execute('SELECT * FROM dns_domains_list()').fetchall() if row['name'] == name), None) if row is None: raise Failure(f'no domain {name}', 3) return row def listing(): """Every domain with its manual records and the records the name server answers for it.""" with database() as connection: manual = connection.execute('SELECT * FROM dns_records_list()').fetchall() return [{**row, 'manual': [{key: item[key] for key in ('name', 'type', 'content', 'ttl')} for item in manual if item['domain'] == row['name']], 'records': connection.execute('SELECT * FROM dns_served(%s)', (row['name'],)).fetchall()} for row in connection.execute('SELECT * FROM dns_domains_list()').fetchall()] def domain_add(body): """Add the domain {name, ttl?}; the domain.""" if not isinstance(body, dict) or not set(body) <= {'name', 'ttl'}: raise Failure('a domain is an object of name and ttl') name, ttl = check_domain(body.get('name')), check_ttl(body.get('ttl')) with database() as connection: names = [row['name'] for row in connection.execute('SELECT * FROM dns_domains_list()').fetchall()] if name in names: raise Failure(f'the domain {name} exists', 4) if len(names) >= DOMAINS_MAX: raise Failure(f'the name server has {DOMAINS_MAX} domains') connection.execute('CALL dns_domain_put(%s, %s)', (name, ttl)) return {'name': name, 'ttl': ttl} def domain_change(name, body): """Change the ttl of the domain; the domain.""" if not isinstance(body, dict) or not set(body) <= {'ttl'}: raise Failure('a change of a domain is an object of ttl') with database() as connection: row = domain(connection, name) ttl = check_ttl(body.get('ttl', row['ttl'])) connection.execute('CALL dns_domain_put(%s, %s)', (name, ttl)) return {'name': name, 'ttl': ttl} def domain_remove(name): """Remove the domain with its manual records.""" with database() as connection: domain(connection, name) connection.execute('CALL dns_domain_remove(%s)', (name,)) return {'name': name} def secondary_addresses(cfg): """The addresses dns.secondary resolves to, which are notified of the zones' changes and may transfer them; none while it is not set, the domains then having the primary as their only name server, and none, with a warning, while it does not resolve.""" secondary = cfg['dns']['secondary'].strip() if not secondary: return [] try: found = socket.getaddrinfo(secondary, 53, proto=socket.IPPROTO_UDP) except OSError as exc: linuxmanager.warn(f'dns.secondary {secondary} does not resolve, so it may not transfer the domains: {exc}') return [] return list(dict.fromkeys(str(ipaddress.ip_address(item[4][0])) for item in found)) def add(cfg, name, record): """Add the manual record to the domain, or set the TTL of the same one; the record. A name in a domain below it belongs to that domain.""" with database() as connection: row = domain(connection, name) record = check_record(name, record) record['ttl'] = record['ttl'] or row['ttl'] or cfg['dns']['ttl'] zones = [item['name'] for item in connection.execute('SELECT * FROM dns_domains_list()').fetchall()] owner = closest(zones, record['name']) if owner != name: raise Failure(f'{record["name"]} is in the domain {owner}') records = [item for item in connection.execute('SELECT * FROM dns_records_list()').fetchall() if item['domain'] == name] same = [item for item in records if (item['name'], item['type']) == (record['name'], record['type'])] others = [item for item in records if item['name'] == record['name'] and item['type'] != record['type']] if len(records) >= MANUAL_MAX and not same: raise Failure(f'the domain {name} has {MANUAL_MAX} manual records') if record['type'] == 'CNAME' and (others or [item for item in same if item['content'] != record['content']]): raise Failure(f'{record["name"]} has other records; a CNAME record must be its only record') if any(item['type'] == 'CNAME' for item in others): raise Failure(f'{record["name"]} has a CNAME record, which must be its only record') connection.execute('CALL dns_record_put(%s, %s, %s, %s, %s)', (name, record['name'], record['type'], record['content'], record['ttl'])) return record def remove(name, record_name, kind, content): """Remove the manual records of the name and type in the domain, only the one of the content when it is given.""" full = absolute(name, record_name) with database() as connection: domain(connection, name) found = [row for row in connection.execute('SELECT * FROM dns_records_list()').fetchall() if (row['domain'], row['name'], row['type']) == (name, full, kind) and content in (None, row['content'])] if not found: raise Failure(f'no {kind} record of {full}', 3) connection.execute('CALL dns_record_remove(%s, %s, %s, %s)', (name, full, kind, content)) return {'name': full, 'type': kind, 'removed': len(found)} def records(cfg, row, zones, hosts, manual_records): """The records of the domain row besides its SOA, as (name, type, content, ttl): the NS of the domain and of the domains directly below it, wan.local_fqdn and dns.secondary, the A or AAAA record of each host name of hosts, pairs of a host name and an address, whose closest domain it is, and its manual records.""" dns = cfg['dns'] zone, ttl = row['name'], row['ttl'] or dns['ttl'] servers = [cfg['wan']['local_fqdn'].strip(), *([dns['secondary'].strip()] if dns['secondary'].strip() else [])] children = [name for name in zones if name != zone and closest([item for item in zones if item != name], name) == zone] found = [(name, 'NS', server, ttl) for name in [zone, *children] for server in servers] for host, address in hosts: if closest(zones, host) == zone: address = ipaddress.ip_address(address) found.append((host, 'A' if address.version == 4 else 'AAAA', str(address), ttl)) taken = {(name, kind) for name, kind, _, _ in found} found += [(item['name'], item['type'], item['content'], item['ttl']) for item in manual_records if (item['name'], item['type']) not in taken] return list(dict.fromkeys(found)) def apply(cfg, hosts): """Make the name server the primary of every domain with records(), hosts being the pairs of a host name and an address of the sites with dns router, and of none while dns.enabled is false.""" with database() as connection: if not cfg['dns']['enabled']: connection.execute('CALL dns_retain(%s::text[])', ([],)) return dns = cfg['dns'] domains = connection.execute('SELECT * FROM dns_domains_list()').fetchall() zones = [row['name'] for row in domains] for host, _ in hosts: if closest(zones, host) is None: linuxmanager.warn(f'{host} is in none of the domains, so the name server has no record of it') manual = {} for item in connection.execute('SELECT * FROM dns_records_list()').fetchall(): manual.setdefault(item['domain'], []).append(item) transfers = secondary_addresses(cfg) if domains else [] for row in domains: zone, ttl = row['name'], row['ttl'] or dns['ttl'] rows = records(cfg, row, zones, hosts, manual.get(zone, [])) soa = f'{cfg["wan"]["local_fqdn"].strip()} hostmaster.{zone} {{serial}} {SOA_TIMES} {ttl}' connection.execute('CALL dns_apply(%s, %s, %s, %s::text[], %s::text[], %s::text[], %s::integer[], ' '%s::text[])', (zone, soa, ttl, [item[0] for item in rows], [item[1] for item in rows], [item[2] for item in rows], [item[3] for item in rows], transfers)) connection.execute('CALL dns_retain(%s::text[])', (zones,)) def config_text(addresses): """The settings of PowerDNS: the gpgsql backend on the database of the name server, primary operation, and the addresses it answers on.""" password = DATABASE_SECRET.read_text(encoding='utf-8').strip() return '\n'.join([ '# Written by linux-manager-setup from /etc/linux-manager/linux-manager.json; edits are overwritten.', 'launch=gpgsql', 'gpgsql-host=localhost', f'gpgsql-dbname={DATABASE}', f'gpgsql-user={DATABASE}', f'gpgsql-password={password}', 'primary=yes', f'local-address={", ".join(addresses)}', 'local-port=53', '', ])