from __future__ import annotations import hashlib import hmac import ipaddress import os import re import secrets import shutil import subprocess import tempfile import threading from dataclasses import dataclass from datetime import datetime from pathlib import Path from urllib.parse import urlsplit from flask import Flask, abort, flash, redirect, render_template_string, request, session, url_for # ----------------------------------------------------------------------------- # Configuration # ----------------------------------------------------------------------------- CADDYFILE = Path(os.getenv("CADDYFILE", "/etc/caddy/Caddyfile")).resolve() DNSMASQ_CONF = Path(os.getenv("DNSMASQ_CONF", "/etc/dnsmasq.conf")).resolve() BACKUP_DIR = Path(os.getenv("BACKUP_DIR", "/var/backups/nas-config-web")) try: DNSMASQ_TARGET_IP = str( ipaddress.ip_address(os.getenv("DNSMASQ_TARGET_IP", "192.168.7.251").strip()) ) except ValueError as exc: raise RuntimeError("DNSMASQ_TARGET_IP is not a valid IPv4/IPv6 address.") from exc BEGIN_MARKER = os.getenv("BEGIN_MARKER", "#begin marker") END_MARKER = os.getenv("END_MARKER", "#end marker") ADMIN_USER = os.getenv("ADMIN_USER", "admin") ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "") APP_SECRET = os.getenv("APP_SECRET", secrets.token_urlsafe(48)) LAN_NETWORKS = [ x.strip() for x in os.getenv("LAN_NETWORKS", "192.168.7.0/24,10.10.10.0/24").split(",") if x.strip() ] MAX_BACKUPS = int(os.getenv("MAX_BACKUPS", "50")) CADDY_VALIDATE_CMD = [ os.getenv("CADDY_BIN", "/usr/bin/caddy"), "validate", "--config", str(CADDYFILE), "--adapter", "caddyfile", ] CADDY_APPLY_CMD = ["/usr/bin/systemctl", "reload", "caddy"] DNSMASQ_VALIDATE_CMD = [ os.getenv("DNSMASQ_BIN", "/usr/sbin/dnsmasq"), "--test", f"--conf-file={DNSMASQ_CONF}", ] DNSMASQ_APPLY_CMD = ["/usr/bin/systemctl", "restart", "dnsmasq"] if not ADMIN_PASSWORD: raise RuntimeError( "ADMIN_PASSWORD is not configured. Set it in the systemd EnvironmentFile." ) app = Flask(__name__) app.secret_key = APP_SECRET app.config.update( SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Strict", ) CHANGE_LOCK = threading.Lock() # ----------------------------------------------------------------------------- # Models / parsing # ----------------------------------------------------------------------------- @dataclass class CaddyRecord: record_id: str site: str target: str comment: str lan_only: bool start: int end: int raw: str @dataclass class DnsRecord: record_id: str domain: str ip: str index: int raw: str def _hash_id(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] @dataclass(frozen=True) class ManagedSection: # prefix includes the complete begin-marker line and its original newline. # suffix starts at the end-marker line. Both are copied verbatim when a # managed section is changed, so text outside the markers cannot be altered. prefix: str managed_text: str suffix: str def _marker_pattern(marker: str) -> re.Pattern[str]: marker = marker.strip() if not marker: raise ValueError("Marker cannot be empty.") # A marker must occupy a whole logical line. Case is ignored so existing # '#Begin marker' and '#begin marker' variants are both accepted. return re.compile( rf"(?im)^[ \t]*{re.escape(marker)}[ \t]*(?:\r?\n|$)" ) def split_managed_section(text: str) -> ManagedSection: begin_matches = list(_marker_pattern(BEGIN_MARKER).finditer(text)) end_matches = list(_marker_pattern(END_MARKER).finditer(text)) if len(begin_matches) != 1 or len(end_matches) != 1: raise ValueError( "Config must contain exactly one begin marker and exactly one end marker. " f"Found begin={len(begin_matches)}, end={len(end_matches)}." ) begin = begin_matches[0] end = end_matches[0] if end.start() < begin.end(): raise ValueError("End marker must appear after begin marker.") return ManagedSection( prefix=text[: begin.end()], managed_text=text[begin.end() : end.start()], suffix=text[end.start() :], ) def get_managed_lines(text: str) -> list[str]: return split_managed_section(text).managed_text.splitlines() def replace_managed_lines(text: str, managed: list[str]) -> str: section = split_managed_section(text) # Only the text BETWEEN markers is generated. Prefix and suffix are reused # byte-for-byte at the Unicode text level from the original file. newline = ( "\r\n" if "\r\n" in section.managed_text or section.prefix.endswith("\r\n") else "\n" ) managed_text = newline.join(managed) if managed_text: # The end marker must remain on its own line. This newline is still # inside the managed section, immediately before the end marker. managed_text += newline return section.prefix + managed_text + section.suffix def assert_outside_markers_unchanged(old_text: str, new_text: str) -> None: old = split_managed_section(old_text) new = split_managed_section(new_text) if old.prefix != new.prefix or old.suffix != new.suffix: raise ValueError( "Safety check failed: content outside the managed markers changed. " "Nothing was written." ) def _brace_delta(line: str) -> int: """Count braces outside double quotes/backticks and before comments.""" delta = 0 quote = None escaped = False for ch in line: if escaped: escaped = False continue if ch == "\\" and quote == '"': escaped = True continue if quote: if ch == quote: quote = None continue if ch in ('"', "`"): quote = ch continue if ch == "#": break if ch == "{": delta += 1 elif ch == "}": delta -= 1 return delta def parse_caddy_records(managed: list[str]) -> list[CaddyRecord]: records: list[CaddyRecord] = [] i = 0 while i < len(managed): stripped = managed[i].strip() if not stripped or stripped.startswith("#") or "{" not in managed[i]: i += 1 continue header = managed[i].split("{", 1)[0].strip() if not header: i += 1 continue depth = 0 end = i found_open = False for j in range(i, len(managed)): d = _brace_delta(managed[j]) if d > 0: found_open = True depth += d end = j if found_open and depth == 0: break else: # Let caddy validate report the malformed structure; don't make it deletable. i += 1 continue # Attach immediately preceding comment lines to this record so delete is tidy. start = i k = i - 1 while k >= 0 and managed[k].strip().startswith("#"): start = k k -= 1 raw_lines = managed[start : end + 1] raw = "\n".join(raw_lines) comments = [ line.strip()[1:].strip() for line in managed[start:i] if line.strip().startswith("#") ] comment = " / ".join(x for x in comments if x) m = re.search(r"(?m)^\s*reverse_proxy\s+([^\s{]+)", raw) target = m.group(1) if m else "—" lan_only = bool(re.search(r"(?m)^\s*@\w+\s+remote_ip\s+", raw)) records.append( CaddyRecord( record_id=_hash_id(raw), site=header, target=target, comment=comment, lan_only=lan_only, start=start, end=end, raw=raw, ) ) i = end + 1 return records def parse_dns_records(managed: list[str]) -> list[DnsRecord]: records: list[DnsRecord] = [] rx = re.compile(r"^\s*address=/([^/]+)/([^/\s]+)\s*$") for idx, line in enumerate(managed): m = rx.match(line) if not m: continue records.append( DnsRecord( record_id=_hash_id(line), domain=m.group(1), ip=m.group(2), index=idx, raw=line, ) ) return records # ----------------------------------------------------------------------------- # Validation helpers # ----------------------------------------------------------------------------- HOST_RE = 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])?$", re.IGNORECASE, ) DOMAIN_RE = 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])?$", re.IGNORECASE, ) def validate_site(value: str) -> str: value = value.strip().lower().rstrip(".") if not HOST_RE.fullmatch(value): raise ValueError("Invalid Caddy hostname.") return value def validate_upstream(value: str) -> str: value = value.strip() try: parsed = urlsplit(value) except ValueError as exc: raise ValueError("Invalid upstream URL.") from exc if parsed.scheme not in {"http", "https"}: raise ValueError("Upstream must start with http:// or https://") if not parsed.hostname: raise ValueError("Upstream must contain a hostname or IP address.") if parsed.username or parsed.password: raise ValueError("Credentials in upstream URL are not allowed.") if parsed.path not in {"", "/"} or parsed.query or parsed.fragment: raise ValueError("Upstream must not contain a path, query, or fragment.") try: port = parsed.port except ValueError as exc: raise ValueError("Invalid upstream port.") from exc if port is not None and not (1 <= port <= 65535): raise ValueError("Invalid upstream port.") return value.rstrip("/") def validate_comment(value: str) -> str: value = " ".join(value.replace("\r", " ").replace("\n", " ").split()).strip() if len(value) > 120: raise ValueError("Comment is too long (max 120 characters).") return value def validate_dns_domain(value: str) -> str: value = value.strip().lower().rstrip(".") leading_dot = value.startswith(".") bare = value[1:] if leading_dot else value if not DOMAIN_RE.fullmatch(bare): raise ValueError("Invalid dnsmasq domain.") return ("." if leading_dot else "") + bare def build_caddy_block(site: str, upstream: str, comment: str, lan_only: bool) -> list[str]: lines: list[str] = [] if comment: lines.append(f"#{comment}") lines.append(f"{site} {{") if lan_only: networks = " ".join(LAN_NETWORKS) lines.extend( [ f" @lan remote_ip {networks}", "", " handle @lan {", f" reverse_proxy {upstream}", " }", "", ' respond "Forbidden" 403', ] ) else: lines.append(f" reverse_proxy {upstream}") lines.append("}") return lines # ----------------------------------------------------------------------------- # File transaction / commands # ----------------------------------------------------------------------------- def read_text_exact(path: Path) -> str: # newline="" disables universal-newline conversion, preserving CRLF/LF # exactly as stored in the source file. with path.open("r", encoding="utf-8", newline="") as fh: return fh.read() def run_cmd(cmd: list[str], timeout: int = 20) -> tuple[bool, str]: try: cp = subprocess.run( cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, check=False, env={**os.environ, "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, ) output = (cp.stdout or "").strip() return cp.returncode == 0, output or f"exit code {cp.returncode}" except (OSError, subprocess.TimeoutExpired) as exc: return False, str(exc) def atomic_write(path: Path, content: str, original_stat: os.stat_result | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) if original_stat is None: original_stat = path.stat() fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent), text=True) tmp = Path(tmp_name) try: with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh: fh.write(content) fh.flush() os.fsync(fh.fileno()) os.chmod(tmp, original_stat.st_mode & 0o7777) os.chown(tmp, original_stat.st_uid, original_stat.st_gid) os.replace(tmp, path) dir_fd = os.open(path.parent, os.O_DIRECTORY) try: os.fsync(dir_fd) finally: os.close(dir_fd) finally: if tmp.exists(): tmp.unlink(missing_ok=True) def create_backup(path: Path, old_text: str) -> Path: BACKUP_DIR.mkdir(parents=True, exist_ok=True) stamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f") backup = BACKUP_DIR / f"{path.name}.{stamp}.bak" with backup.open("w", encoding="utf-8", newline="") as fh: fh.write(old_text) st = path.stat() os.chmod(backup, st.st_mode & 0o7777) prefix = f"{path.name}." backups = sorted( [p for p in BACKUP_DIR.iterdir() if p.name.startswith(prefix) and p.name.endswith(".bak")], key=lambda p: p.stat().st_mtime, reverse=True, ) for stale in backups[MAX_BACKUPS:]: stale.unlink(missing_ok=True) return backup def apply_transaction( path: Path, expected_old_text: str, new_text: str, validate_cmd: list[str], apply_cmd: list[str], ) -> tuple[bool, str]: with CHANGE_LOCK: old_text = read_text_exact(path) if old_text != expected_old_text: return False, "Config file changed since the page action started; nothing was written. Reload the page and try again." if old_text == new_text: return True, "No changes were necessary." # Defence in depth: even if a future route constructs new_text # incorrectly, refuse to write unless everything outside the markers # is exactly unchanged. assert_outside_markers_unchanged(old_text, new_text) stat = path.stat() backup = create_backup(path, old_text) atomic_write(path, new_text, stat) valid, validation_output = run_cmd(validate_cmd) if not valid: atomic_write(path, old_text, stat) return ( False, "Validation failed; original file restored.\n" f"Validator output:\n{validation_output}", ) applied, apply_output = run_cmd(apply_cmd) if applied: return True, f"Applied successfully. Backup: {backup}" # The file was valid, but service action failed. Restore the original # config and make a best-effort attempt to reactivate it. atomic_write(path, old_text, stat) rollback_valid, rollback_validation = run_cmd(validate_cmd) rollback_applied, rollback_apply = run_cmd(apply_cmd) if rollback_valid else (False, "rollback validation failed") details = [ "Service reload/restart failed; original file restored.", f"Apply output: {apply_output}", f"Rollback validation: {rollback_validation}", f"Rollback apply: {rollback_apply}", ] if not rollback_applied: details.append("WARNING: automatic rollback activation also failed; check the service immediately.") return False, "\n".join(details) # ----------------------------------------------------------------------------- # Auth / CSRF # ----------------------------------------------------------------------------- def _auth_ok() -> bool: auth = request.authorization if not auth: return False return hmac.compare_digest(auth.username or "", ADMIN_USER) and hmac.compare_digest( auth.password or "", ADMIN_PASSWORD ) @app.before_request def require_auth(): if not _auth_ok(): return ( "Authentication required", 401, {"WWW-Authenticate": 'Basic realm="NAS Config"'}, ) def csrf_token() -> str: token = session.get("csrf_token") if not token: token = secrets.token_urlsafe(32) session["csrf_token"] = token return token app.jinja_env.globals["csrf_token"] = csrf_token def require_csrf() -> None: expected = session.get("csrf_token", "") supplied = request.form.get("csrf_token", "") if not expected or not hmac.compare_digest(expected, supplied): abort(400, "Invalid CSRF token") # ----------------------------------------------------------------------------- # Routes # ----------------------------------------------------------------------------- def load_state(): caddy_text = read_text_exact(CADDYFILE) dns_text = read_text_exact(DNSMASQ_CONF) caddy_records = parse_caddy_records(get_managed_lines(caddy_text)) dns_records = parse_dns_records(get_managed_lines(dns_text)) caddy_status, caddy_status_text = run_cmd(CADDY_VALIDATE_CMD) dns_status, dns_status_text = run_cmd(DNSMASQ_VALIDATE_CMD) return caddy_records, dns_records, caddy_status, caddy_status_text, dns_status, dns_status_text @app.get("/") def index(): try: state = load_state() except Exception as exc: state = ([], [], False, f"Cannot read Caddy config: {exc}", False, f"Cannot read dnsmasq config: {exc}") return render_template_string( TEMPLATE, caddy_records=state[0], dns_records=state[1], caddy_ok=state[2], caddy_status=state[3], dns_ok=state[4], dns_status=state[5], lan_networks=", ".join(LAN_NETWORKS), dns_target_ip=DNSMASQ_TARGET_IP, ) @app.post("/caddy/add") def caddy_add(): require_csrf() try: site = validate_site(request.form.get("site", "")) upstream = validate_upstream(request.form.get("upstream", "")) comment = validate_comment(request.form.get("comment", "")) lan_only = request.form.get("lan_only") == "on" old = read_text_exact(CADDYFILE) managed = get_managed_lines(old) records = parse_caddy_records(managed) existing_sites = {r.site.strip().lower() for r in records} if site.lower() in existing_sites: raise ValueError(f"Caddy entry for {site} already exists in the managed section.") new_block = build_caddy_block(site, upstream, comment, lan_only) if managed and managed[-1].strip(): managed.append("") managed.extend(new_block) new = replace_managed_lines(old, managed) ok, message = apply_transaction(CADDYFILE, old, new, CADDY_VALIDATE_CMD, CADDY_APPLY_CMD) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.post("/caddy/delete") def caddy_delete(): require_csrf() record_id = request.form.get("record_id", "") try: old = read_text_exact(CADDYFILE) managed = get_managed_lines(old) records = parse_caddy_records(managed) record = next((r for r in records if r.record_id == record_id), None) if record is None: raise ValueError("Caddy record not found; reload the page and try again.") del managed[record.start : record.end + 1] # Collapse excessive blank lines around the removed block. compact: list[str] = [] for line in managed: if line.strip() == "" and compact and compact[-1].strip() == "": continue compact.append(line) while compact and compact[0].strip() == "": compact.pop(0) while compact and compact[-1].strip() == "": compact.pop() new = replace_managed_lines(old, compact) ok, message = apply_transaction(CADDYFILE, old, new, CADDY_VALIDATE_CMD, CADDY_APPLY_CMD) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.post("/dns/add") def dns_add(): require_csrf() try: domain = validate_dns_domain(request.form.get("domain", "")) ip = DNSMASQ_TARGET_IP old = read_text_exact(DNSMASQ_CONF) managed = get_managed_lines(old) records = parse_dns_records(managed) if domain.lower() in {r.domain.lower() for r in records}: raise ValueError(f"dnsmasq entry for {domain} already exists in the managed section.") if managed and managed[-1].strip() == "": managed[-1] = f"address=/{domain}/{ip}" else: managed.append(f"address=/{domain}/{ip}") new = replace_managed_lines(old, managed) ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.post("/dns/delete") def dns_delete(): require_csrf() record_id = request.form.get("record_id", "") try: old = read_text_exact(DNSMASQ_CONF) managed = get_managed_lines(old) records = parse_dns_records(managed) record = next((r for r in records if r.record_id == record_id), None) if record is None: raise ValueError("dnsmasq record not found; reload the page and try again.") del managed[record.index] new = replace_managed_lines(old, managed) ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.get("/health") def health(): return {"ok": True} # ----------------------------------------------------------------------------- # UI # ----------------------------------------------------------------------------- TEMPLATE = r""" NAS Config

NAS Config

Управляемые секции Caddy и dnsmasq. Перед применением конфигурация проверяется, при ошибке выполняется откат.
{% with messages = get_flashed_messages(with_categories=true) %} {% for category, message in messages %}
{{ message }}
{% endfor %} {% endwith %}

Caddy

{{ 'config OK' if caddy_ok else 'config ERROR' }}
{% for r in caddy_records %} {% else %}{% endfor %}
HostUpstream
{{ r.site }}{% if r.comment %}
{{ r.comment }}
{% endif %}{% if r.lan_only %}LAN only{% endif %}
{{ r.target }}
Записей не найдено.
Результат caddy validate
{{ caddy_status }}

dnsmasq

{{ 'config OK' if dns_ok else 'config ERROR' }}
Все новые записи направляются на {{ dns_target_ip }} (настройка DNSMASQ_TARGET_IP).
{% for r in dns_records %} {% else %}{% endfor %}
DomainIP
{{ r.domain }} {{ r.ip }}
Записей не найдено.
Результат dnsmasq --test
{{ dns_status }}
""" if __name__ == "__main__": # For manual testing only. The systemd unit uses gunicorn. app.run(host="127.0.0.1", port=8090, debug=False)