добавлен импорт\экспорт сайтов для dnsmasq и функция отключения авторизации

This commit is contained in:
2026-09-30 22:58:51 +03:00
parent 808db93e48
commit 38a40007fd
3 changed files with 318 additions and 211 deletions
+176 -86
View File
@@ -15,7 +15,7 @@ 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
from flask import Flask, Response, abort, flash, redirect, render_template_string, request, session, url_for
# -----------------------------------------------------------------------------
@@ -26,19 +26,24 @@ 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/web-proxy-config"))
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")
def env_bool(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
AUTH_ENABLED = env_bool("AUTH_ENABLED", True)
ADMIN_USER = os.getenv("ADMIN_USER", "admin")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "")
APP_SECRET = os.getenv("APP_SECRET", secrets.token_urlsafe(48))
DNSMASQ_TARGET_IP = str(
ipaddress.ip_address(os.getenv("DNSMASQ_TARGET_IP", "192.168.7.251").strip())
)
MAX_IMPORT_BYTES = int(os.getenv("MAX_IMPORT_BYTES", str(256 * 1024)))
LAN_NETWORKS = [
x.strip()
for x in os.getenv("LAN_NETWORKS", "192.168.7.0/24,10.10.10.0/24").split(",")
@@ -62,9 +67,10 @@ DNSMASQ_VALIDATE_CMD = [
]
DNSMASQ_APPLY_CMD = ["/usr/bin/systemctl", "restart", "dnsmasq"]
if not ADMIN_PASSWORD:
if AUTH_ENABLED and not ADMIN_PASSWORD:
raise RuntimeError(
"ADMIN_PASSWORD is not configured. Set it in the systemd EnvironmentFile."
"AUTH_ENABLED is true, but ADMIN_PASSWORD is not configured. "
"Set ADMIN_PASSWORD or disable authentication with AUTH_ENABLED=false."
)
app = Flask(__name__)
@@ -107,80 +113,62 @@ 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 _find_marker_line(text: str, marker: str) -> list[re.Match[str]]:
pattern = re.compile(
rf"(?im)^[ \t]*{re.escape(marker.strip())}[ \t]*(?:\r\n|\n|\r|$)"
)
return list(pattern.finditer(text))
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))
def split_managed_section(text: str) -> tuple[str, str, str, str]:
"""Return prefix, managed text, suffix and preferred newline.
if len(begin_matches) != 1 or len(end_matches) != 1:
Prefix includes the begin-marker line and its line ending. Suffix starts with
the end-marker line. Therefore prefix and suffix can be copied byte-for-byte
(at the decoded text level) without being rebuilt.
"""
begins = _find_marker_line(text, BEGIN_MARKER)
ends = _find_marker_line(text, END_MARKER)
if len(begins) != 1 or len(ends) != 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)}."
f"Expected exactly one '{BEGIN_MARKER}' and one '{END_MARKER}' marker."
)
begin = begin_matches[0]
end = end_matches[0]
begin = begins[0]
end = ends[0]
if end.start() < begin.end():
raise ValueError("End marker must appear after begin marker.")
raise ValueError("End marker is before the begin marker.")
return ManagedSection(
prefix=text[: begin.end()],
managed_text=text[begin.end() : end.start()],
suffix=text[end.start() :],
)
prefix = text[: begin.end()]
managed = text[begin.end() : end.start()]
suffix = text[end.start() :]
if prefix.endswith("\r\n"):
newline = "\r\n"
elif prefix.endswith("\n"):
newline = "\n"
elif prefix.endswith("\r"):
newline = "\r"
else:
newline = "\n"
return prefix, managed, suffix, newline
def get_managed_lines(text: str) -> list[str]:
return split_managed_section(text).managed_text.splitlines()
_, managed, _, _ = split_managed_section(text)
return managed.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
prefix, _, suffix, newline = split_managed_section(text)
body = newline.join(managed)
if body:
body += newline
return prefix + body + 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 read_text_exact(path: Path) -> str:
with path.open("r", encoding="utf-8", newline="") as fh:
return fh.read()
def _brace_delta(line: str) -> int:
@@ -359,6 +347,13 @@ def validate_dns_domain(value: str) -> str:
return ("." if leading_dot else "") + bare
def validate_ip(value: str) -> str:
value = value.strip()
try:
return str(ipaddress.ip_address(value))
except ValueError as exc:
raise ValueError("Invalid IP address.") from exc
def build_caddy_block(site: str, upstream: str, comment: str, lan_only: bool) -> list[str]:
lines: list[str] = []
@@ -389,13 +384,6 @@ def build_caddy_block(site: str, upstream: str, comment: str, lan_only: bool) ->
# -----------------------------------------------------------------------------
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(
@@ -472,10 +460,12 @@ def apply_transaction(
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)
# Hard safety boundary: content outside the managed markers must be
# exactly identical before a write is allowed.
old_prefix, _, old_suffix, _ = split_managed_section(old_text)
new_prefix, _, new_suffix, _ = split_managed_section(new_text)
if old_prefix != new_prefix or old_suffix != new_suffix:
return False, "Safety check failed: text outside the markers changed; nothing was written."
stat = path.stat()
backup = create_backup(path, old_text)
@@ -527,11 +517,11 @@ def _auth_ok() -> bool:
@app.before_request
def require_auth():
if not _auth_ok():
if AUTH_ENABLED and not _auth_ok():
return (
"Authentication required",
401,
{"WWW-Authenticate": 'Basic realm="NAS Config"'},
{"WWW-Authenticate": 'Basic realm="Proxy Config"'},
)
@@ -584,6 +574,7 @@ def index():
dns_status=state[5],
lan_networks=", ".join(LAN_NETWORKS),
dns_target_ip=DNSMASQ_TARGET_IP,
auth_enabled=AUTH_ENABLED,
)
@@ -692,6 +683,94 @@ def dns_delete():
return redirect(url_for("index"))
@app.post("/dns/import")
def dns_import():
require_csrf()
try:
upload = request.files.get("file")
if upload is None or not upload.filename:
raise ValueError("Выберите текстовый файл со списком доменов.")
data = upload.stream.read(MAX_IMPORT_BYTES + 1)
if len(data) > MAX_IMPORT_BYTES:
raise ValueError(f"Файл слишком большой. Максимальный размер: {MAX_IMPORT_BYTES} байт.")
try:
imported_text = data.decode("utf-8-sig")
except UnicodeDecodeError as exc:
raise ValueError("Файл импорта должен быть в кодировке UTF-8.") from exc
domains: list[str] = []
seen_import: set[str] = set()
errors: list[str] = []
for lineno, raw_line in enumerate(imported_text.splitlines(), start=1):
line = raw_line.strip()
if not line or line.startswith("#"):
continue
try:
domain = validate_dns_domain(line)
except ValueError:
errors.append(f"строка {lineno}: {line}")
continue
key = domain.lower()
if key not in seen_import:
seen_import.add(key)
domains.append(domain)
if errors:
preview = "; ".join(errors[:8])
if len(errors) > 8:
preview += f"; ещё {len(errors) - 8}"
raise ValueError(f"В файле есть некорректные домены: {preview}")
if not domains:
raise ValueError("В файле не найдено ни одного домена.")
old = read_text_exact(DNSMASQ_CONF)
managed = get_managed_lines(old)
records = parse_dns_records(managed)
existing = {r.domain.lower() for r in records}
added = 0
skipped = 0
for domain in domains:
if domain.lower() in existing:
skipped += 1
continue
managed.append(f"address=/{domain}/{DNSMASQ_TARGET_IP}")
existing.add(domain.lower())
added += 1
if not added:
flash(f"Новых доменов нет. Пропущено существующих: {skipped}.", "success")
return redirect(url_for("index"))
new = replace_managed_lines(old, managed)
ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD)
if ok:
message = f"Импорт завершён: добавлено {added}, пропущено существующих {skipped}.\n{message}"
flash(message, "success" if ok else "error")
except Exception as exc:
flash(str(exc), "error")
return redirect(url_for("index"))
@app.get("/dns/export")
def dns_export():
try:
text = read_text_exact(DNSMASQ_CONF)
records = parse_dns_records(get_managed_lines(text))
content = "\n".join(r.domain for r in records)
if content:
content += "\n"
return Response(
content,
mimetype="text/plain; charset=utf-8",
headers={"Content-Disposition": "attachment; filename=dnsmasq-sites.txt"},
)
except Exception as exc:
flash(str(exc), "error")
return redirect(url_for("index"))
@app.get("/health")
def health():
return {"ok": True}
@@ -707,7 +786,7 @@ TEMPLATE = r"""
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>NAS Config</title>
<title>Proxy Config</title>
<style>
:root { color-scheme: dark; --bg:#101318; --card:#171b22; --muted:#8f99a8; --line:#2b313c; --good:#35c46a; --bad:#ff5d66; --accent:#5b9cff; }
* { box-sizing:border-box; }
@@ -730,6 +809,9 @@ TEMPLATE = r"""
.check { display:flex; gap:8px; align-items:center; color:#dce3eb; }
button { border:0; border-radius:8px; padding:9px 12px; color:#fff; background:var(--accent); cursor:pointer; font-weight:600; }
button.delete { background:transparent; color:#ff8c92; border:1px solid #65343a; padding:6px 9px; }
.button-link { display:inline-block; border-radius:8px; padding:9px 12px; color:#fff; background:#394456; text-decoration:none; font-weight:600; text-align:center; }
input[type=file] { width:100%; margin-top:5px; color:#cdd6e3; }
.dns-tools { display:grid; grid-template-columns:1fr auto; gap:10px; margin-bottom:16px; padding:13px; background:#12161c; border:1px solid var(--line); border-radius:11px; align-items:end; }
table { width:100%; border-collapse:collapse; }
th { text-align:left; font-size:11px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); padding:8px 7px; border-bottom:1px solid var(--line); }
td { padding:10px 7px; border-bottom:1px solid #242a33; vertical-align:top; }
@@ -746,8 +828,9 @@ TEMPLATE = r"""
</head>
<body>
<main>
<h1>NAS Config</h1>
<h1>Proxy Config</h1>
<div class="muted">Управляемые секции Caddy и dnsmasq. Перед применением конфигурация проверяется, при ошибке выполняется откат.</div>
<div class="muted">Авторизация: {{ 'включена' if auth_enabled else 'отключена' }}.</div>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
@@ -757,7 +840,7 @@ TEMPLATE = r"""
<section class="card">
<div class="head">
<h2>Caddy</h2>
<span class="status"><span class="dot {{ 'ok' if caddy_ok else '' }}"></span>{{ 'config OK' if caddy_ok else 'config ERROR' }}</span>
<span class="status"><span class="dot {{ 'ok' if caddy_ok else '' }}"></span>{{ 'конфигурация OK' if caddy_ok else 'ошибка конфигурации' }}</span>
</div>
<form class="add" method="post" action="{{ url_for('caddy_add') }}">
@@ -793,16 +876,23 @@ TEMPLATE = r"""
<section class="card">
<div class="head">
<h2>dnsmasq</h2>
<span class="status"><span class="dot {{ 'ok' if dns_ok else '' }}"></span>{{ 'config OK' if dns_ok else 'config ERROR' }}</span>
<span class="status"><span class="dot {{ 'ok' if dns_ok else '' }}"></span>{{ 'конфигурация OK' if dns_ok else 'ошибка конфигурации' }}</span>
</div>
<form class="add" method="post" action="{{ url_for('dns_add') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label class="wide">Домен<input type="text" name="domain" required placeholder="example.com или .example.com"></label>
<div class="muted wide">Все новые записи направляются на <code>{{ dns_target_ip }}</code> (настройка DNSMASQ_TARGET_IP).</div>
<div class="wide muted">Все новые записи направляются на {{ dns_target_ip }}.</div>
<button class="wide" type="submit">Добавить DNS-запись</button>
</form>
<form class="dns-tools" method="post" action="{{ url_for('dns_import') }}" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label>Импорт списка доменов (.txt, один домен на строку)<input type="file" name="file" accept=".txt,text/plain" required></label>
<button type="submit">Импортировать</button>
</form>
<p><a class="button-link" href="{{ url_for('dns_export') }}">Экспортировать список доменов</a></p>
<table>
<thead><tr><th>Domain</th><th>IP</th><th></th></tr></thead>
<tbody>