Files
Amnezia-Web-Panel/managers/dns_manager.py
T
hellandClaude Opus 5 69893ba340 feat(exit): route client traffic through another panel server
Today a client leaves to the internet from the same server it connected to.
Exit nodes split the two: clients connect to an *entry* node (reachable,
possibly behind DPI) and egress from an *exit* node (clean IP, other country).
One exit serves many entries and keeps serving its own AWG clients.

    client --AWG--> [entry] amnezia-awg2 --WG/AWG link--> [exit] amnezia-exit --> internet
                    awg0 10.8.1.0/24                     transit0 10.9.0.0/24
                    exit0 10.9.0.N (Table=off)           one [Peer] per entry, /32

Exit side: a new protocol `exit` = container `amnezia-exit`, an AmneziaWG
listener on 55520/udp over the transit subnet 10.9.0.0/24. Peers are panel
nodes, never end users, and live in their own peersTable. ExitManager
subclasses AWGManager and closes every client-facing method.

Entry side: a second interface `exit0` inside the existing AWG container with
`Table = off`, plus policy routing - `from <client subnet> lookup 200`,
`default dev exit0` in table 200, and `blackhole default metric 1000` as a
kill-switch installed *before* the client tunnel comes up, so a container
restart cannot leak. Clients are MASQUERADEd into the entry's transit /32, so
the identical 10.8.1.0/24 of every instance can never collide at the exit.
TCP MSS is clamped, and rules 190/191 keep client<->client and AmneziaDNS
traffic local. State is file-driven: exit0.conf present means linked, and the
same shell block runs at container start and on a live (un)link.

Link crypto is WireGuard; AWG obfuscation is a per-exit-node property for hops
that cross DPI, and S3/S4 are deliberately not written on the transit - they
pad every transport packet and would eat the MTU budget of a tunnel inside a
tunnel. Private keys are generated inside the containers; the panel carries
public keys and a per-peer PSK only.

exit_link_service.py orchestrates linking with per-(entry, protocol) locks,
SSH off the event loop, a 15-second handshake gate that rolls back, and
lifecycle hooks for every way a link can go stale: exit uninstalled, stopped,
deleted, host cleared, entry reinstalled, container gone, backup restored.
Servers get a stable `uid` (already upstream) so reorder and delete cannot
break a link.

IPv4 only for now: while linked, client IPv6 is refused with `unreachable`
rather than leaking out of the entry.

Also included: an egress check that curls a public IP service bound to the
tunnel gateway (the client's exact path) and compares it with the direct one;
optional DNS resolution at the exit node; a default exit node applied to new
AWG installs; and reconciliation after a protocol restore.

244 tests pass. CURRENT_VERSION is untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 23:05:51 +07:00

84 lines
3.6 KiB
Python

import os
import logging
logger = logging.getLogger(__name__)
class DNSManager:
def __init__(self, ssh):
self.ssh = ssh
def install_protocol(self, protocol_type='dns', port='53'):
"""Install AmneziaDNS service."""
try:
# 1. Check if docker is installed
out, _, _ = self.ssh.run_command("docker --version")
if "docker version" not in out.lower():
return {"status": "error", "message": "Docker not installed"}
# 2. Prepare directory
self.ssh.run_sudo_command("mkdir -p /opt/amnezia/dns")
# 3. Create Dockerfile matching official Amnezia implementation
# We use Unbound (mvance/unbound) with DNS-over-TLS to Cloudflare
forward_config = """forward-zone:
name: "."
forward-tls-upstream: yes
forward-addr: 1.1.1.1@853
forward-addr: 1.0.0.1@853
"""
self.ssh.write_file("/opt/amnezia/dns/forward-records.conf", forward_config)
dockerfile = """
FROM mvance/unbound:latest
LABEL maintainer="AmneziaVPN"
COPY forward-records.conf /opt/unbound/etc/unbound/forward-records.conf
"""
self.ssh.write_file("/opt/amnezia/dns/Dockerfile", dockerfile)
# 4. Build and run
self.ssh.run_sudo_command("docker build -t amnezia-dns /opt/amnezia/dns")
self.ssh.run_sudo_command("docker stop amnezia-dns || true")
self.ssh.run_sudo_command("docker rm amnezia-dns || true")
# Create internal network for DNS (like original Amnezia client)
self.ssh.run_sudo_command("docker network ls | grep -q amnezia-dns-net || docker network create --subnet 172.29.172.0/24 amnezia-dns-net")
# Use internal network with static IP. Do not expose 53 on host to avoid systemd-resolved conflict.
cmd = "docker run -d --name amnezia-dns --restart always --network amnezia-dns-net --ip=172.29.172.254 amnezia-dns"
self.ssh.run_sudo_command(cmd)
# Connect existing VPN containers to the DNS network
vpn_containers = ['amnezia-awg', 'amnezia-awg2', 'amnezia-awg-legacy', 'amnezia-xray', 'telemt', 'amnezia-exit']
for c in vpn_containers:
self.ssh.run_sudo_command(f"docker ps | grep -q {c} && docker network connect amnezia-dns-net {c} || true")
return {"status": "success", "message": "AmneziaDNS installed successfully"}
except Exception as e:
logger.exception("Error installing DNS")
return {"status": "error", "message": str(e)}
def get_server_status(self, protocol_type='dns'):
"""Check if AmneziaDNS container is running."""
try:
out, _, _ = self.ssh.run_sudo_command("docker ps --filter name=^amnezia-dns$ --format '{{.Status}}'")
is_running = 'Up' in out
out_exists, _, _ = self.ssh.run_sudo_command("docker ps -a --filter name=^amnezia-dns$ --format '{{.Names}}'")
container_exists = 'amnezia-dns' in out_exists.strip().split('\n')
return {
"container_exists": container_exists,
"container_running": is_running,
"port": "53",
"protocol": protocol_type
}
except Exception as e:
return {"error": str(e)}
def remove_container(self, protocol_type='dns'):
"""Remove AmneziaDNS container."""
self.ssh.run_sudo_command("docker stop amnezia-dns || true")
self.ssh.run_sudo_command("docker rm amnezia-dns || true")
self.ssh.run_sudo_command("rm -rf /opt/amnezia/dns")