Template
Fix cascade silent dead internet with per-step settings and handshake checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -46,7 +46,7 @@ from managers.awg_manager import AWGManager
|
||||
from managers.xray_manager import XrayManager
|
||||
from managers.wireguard_manager import WireGuardManager
|
||||
from managers.backup_manager import BackupManager
|
||||
from managers.cascade_manager import CascadeManager
|
||||
from managers.cascade_manager import CascadeManager, normalize_settings, DEFAULT_SETTINGS as CASCADE_DEFAULT_SETTINGS
|
||||
import telegram_bot as tg_bot
|
||||
|
||||
# Configure logging
|
||||
@@ -1449,6 +1449,18 @@ class CascadeSetupRequest(BaseModel):
|
||||
exit_server_id: Optional[int] = None
|
||||
exit_protocol: str = 'awg2'
|
||||
enabled: bool = True
|
||||
# Per-step cascade tuning
|
||||
pin_exit_route: Optional[bool] = True
|
||||
remove_eth_masquerade: Optional[bool] = True
|
||||
force_forward: Optional[bool] = True
|
||||
mss_clamp: Optional[bool] = True
|
||||
wait_handshake: Optional[bool] = True
|
||||
handshake_timeout_sec: Optional[int] = 25
|
||||
allowed_ips: Optional[str] = '0.0.0.0/0, ::/0'
|
||||
keep_exit_dns: Optional[bool] = False
|
||||
vpn_subnet_override: Optional[str] = ''
|
||||
table_id: Optional[int] = 200
|
||||
rule_priority: Optional[int] = 100
|
||||
|
||||
|
||||
class ContainerLogsRequest(BaseModel):
|
||||
@@ -2792,6 +2804,7 @@ async def api_cascade_get(request: Request, server_id: int):
|
||||
return {
|
||||
'cascade': cascade,
|
||||
'live': live,
|
||||
'defaults': CASCADE_DEFAULT_SETTINGS,
|
||||
'servers': [
|
||||
{
|
||||
'id': i,
|
||||
@@ -2822,12 +2835,28 @@ async def api_cascade_setup(request: Request, server_id: int, req: CascadeSetupR
|
||||
if server_id >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Server not found'}, status_code=404)
|
||||
entry = data['servers'][server_id]
|
||||
settings = normalize_settings({
|
||||
'pin_exit_route': req.pin_exit_route,
|
||||
'remove_eth_masquerade': req.remove_eth_masquerade,
|
||||
'force_forward': req.force_forward,
|
||||
'mss_clamp': req.mss_clamp,
|
||||
'wait_handshake': req.wait_handshake,
|
||||
'handshake_timeout_sec': req.handshake_timeout_sec,
|
||||
'allowed_ips': req.allowed_ips,
|
||||
'keep_exit_dns': req.keep_exit_dns,
|
||||
'vpn_subnet_override': req.vpn_subnet_override,
|
||||
'table_id': req.table_id,
|
||||
'rule_priority': req.rule_priority,
|
||||
})
|
||||
if not req.enabled:
|
||||
def _disable():
|
||||
ssh = get_ssh(entry)
|
||||
ssh.connect()
|
||||
try:
|
||||
return CascadeManager(ssh).disable(req.entry_protocol)
|
||||
return CascadeManager(ssh).disable(
|
||||
req.entry_protocol,
|
||||
settings=dict((entry.get('cascade') or {}).get('settings') or settings),
|
||||
)
|
||||
finally:
|
||||
ssh.disconnect()
|
||||
|
||||
@@ -2840,6 +2869,7 @@ async def api_cascade_setup(request: Request, server_id: int, req: CascadeSetupR
|
||||
'entry_protocol': req.entry_protocol or prev.get('entry_protocol'),
|
||||
'exit_server_id': prev.get('exit_server_id'),
|
||||
'exit_protocol': prev.get('exit_protocol') or req.exit_protocol,
|
||||
'settings': settings,
|
||||
'updated_at': datetime.now().isoformat(timespec='seconds'),
|
||||
}
|
||||
await save_data_async(data)
|
||||
@@ -2914,6 +2944,7 @@ async def api_cascade_setup(request: Request, server_id: int, req: CascadeSetupR
|
||||
req.entry_protocol,
|
||||
conf,
|
||||
exit_srv.get('host') or '',
|
||||
settings=settings,
|
||||
)
|
||||
finally:
|
||||
entry_ssh.disconnect()
|
||||
@@ -2928,6 +2959,7 @@ async def api_cascade_setup(request: Request, server_id: int, req: CascadeSetupR
|
||||
}
|
||||
|
||||
info = await asyncio.to_thread(_enable)
|
||||
applied = info.get('applied') or {}
|
||||
entry['cascade'] = {
|
||||
'enabled': True,
|
||||
'entry_protocol': req.entry_protocol,
|
||||
@@ -2935,12 +2967,15 @@ async def api_cascade_setup(request: Request, server_id: int, req: CascadeSetupR
|
||||
'exit_protocol': req.exit_protocol,
|
||||
'exit_client_id': info['client_id'],
|
||||
'exit_client_name': info['client_name'],
|
||||
'up': bool((info.get('applied') or {}).get('up')),
|
||||
'settings': settings,
|
||||
'up': bool(applied.get('up')),
|
||||
'handshake': bool(applied.get('handshake')),
|
||||
'updated_at': datetime.now().isoformat(timespec='seconds'),
|
||||
'last_error': None,
|
||||
'diagnostics': applied.get('diagnostics') or '',
|
||||
}
|
||||
await save_data_async(data)
|
||||
return {'status': 'success', 'cascade': entry['cascade'], 'applied': info.get('applied')}
|
||||
return {'status': 'success', 'cascade': entry['cascade'], 'applied': applied}
|
||||
except Exception as e:
|
||||
logger.exception("Error setting up cascade")
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
+199
-45
@@ -12,11 +12,50 @@ from __future__ import annotations
|
||||
import re
|
||||
import shlex
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
WG_FAMILY = {'awg', 'awg2', 'awg_legacy', 'wireguard'}
|
||||
CASCADE_MARKER = '# amnezia-web-panel-cascade'
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
'pin_exit_route': True, # host route to exit IP via real gateway
|
||||
'remove_eth_masquerade': True, # stop NATing VPN clients out entry eth0/eth1
|
||||
'force_forward': True, # FORWARD accept between awg0/wg0 and cascade
|
||||
'mss_clamp': True, # fix broken TCP / endless page load
|
||||
'wait_handshake': True, # fail if exit tunnel has no handshake
|
||||
'handshake_timeout_sec': 25,
|
||||
'allowed_ips': '0.0.0.0/0, ::/0',
|
||||
'keep_exit_dns': False, # keep DNS= from exit client config
|
||||
'vpn_subnet_override': '', # e.g. 10.8.1.0/24; empty = auto
|
||||
'table_id': 200,
|
||||
'rule_priority': 100,
|
||||
}
|
||||
|
||||
|
||||
def normalize_settings(raw: Optional[dict]) -> dict:
|
||||
settings = dict(DEFAULT_SETTINGS)
|
||||
if isinstance(raw, dict):
|
||||
for key, default in DEFAULT_SETTINGS.items():
|
||||
if key not in raw or raw[key] is None:
|
||||
continue
|
||||
if isinstance(default, bool):
|
||||
settings[key] = bool(raw[key])
|
||||
elif isinstance(default, int):
|
||||
try:
|
||||
settings[key] = int(raw[key])
|
||||
except (TypeError, ValueError):
|
||||
settings[key] = default
|
||||
else:
|
||||
settings[key] = str(raw[key]).strip()
|
||||
# Sanity clamps
|
||||
settings['handshake_timeout_sec'] = max(5, min(120, int(settings['handshake_timeout_sec'])))
|
||||
settings['table_id'] = max(1, min(252, int(settings['table_id'])))
|
||||
settings['rule_priority'] = max(1, min(32765, int(settings['rule_priority'])))
|
||||
if not settings.get('allowed_ips'):
|
||||
settings['allowed_ips'] = DEFAULT_SETTINGS['allowed_ips']
|
||||
return settings
|
||||
|
||||
|
||||
class CascadeManager:
|
||||
def __init__(self, ssh_manager):
|
||||
@@ -76,20 +115,27 @@ class CascadeManager:
|
||||
return '/opt/amnezia/awg/awg0.conf'
|
||||
|
||||
@staticmethod
|
||||
def prepare_exit_client_config(raw_config: str, endpoint_host: str) -> str:
|
||||
def prepare_exit_client_config(
|
||||
raw_config: str,
|
||||
endpoint_host: str,
|
||||
*,
|
||||
keep_dns: bool = False,
|
||||
allowed_ips: str = '0.0.0.0/0, ::/0',
|
||||
) -> str:
|
||||
"""Adapt a normal client config for use as an entry→exit cascade tunnel."""
|
||||
lines = []
|
||||
in_interface = False
|
||||
in_peer = False
|
||||
has_table = False
|
||||
for raw in (raw_config or '').splitlines():
|
||||
line = raw.rstrip('\n')
|
||||
stripped = line.strip()
|
||||
stripped = raw.strip()
|
||||
lower = stripped.lower()
|
||||
if stripped.startswith('[') and stripped.endswith(']'):
|
||||
in_interface = stripped.lower() == '[interface]'
|
||||
in_peer = stripped.lower() == '[peer]'
|
||||
lines.append(stripped)
|
||||
continue
|
||||
if in_interface and lower.startswith('dns'):
|
||||
if in_interface and lower.startswith('dns') and not keep_dns:
|
||||
continue
|
||||
if in_interface and lower.startswith('table'):
|
||||
has_table = True
|
||||
@@ -107,6 +153,9 @@ class CascadeManager:
|
||||
else:
|
||||
lines.append(stripped)
|
||||
continue
|
||||
if in_peer and lower.startswith('allowedips'):
|
||||
lines.append(f'AllowedIPs = {allowed_ips}')
|
||||
continue
|
||||
lines.append(stripped)
|
||||
|
||||
if not has_table:
|
||||
@@ -131,29 +180,44 @@ class CascadeManager:
|
||||
def status(self, entry_protocol: str) -> dict:
|
||||
container = self._container_name(entry_protocol)
|
||||
if not container:
|
||||
return {'enabled': False, 'up': False, 'error': 'Unsupported protocol'}
|
||||
return {'enabled': False, 'up': False, 'handshake': False, 'error': 'Unsupported protocol'}
|
||||
conf = self._cascade_conf(entry_protocol)
|
||||
wg_bin = self._wg_binary(entry_protocol)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} bash -lc "
|
||||
f"'test -f {shlex.quote(conf)} && echo HAS_CONF; "
|
||||
f"ip -o link show cascade 2>/dev/null | head -1; "
|
||||
f"{wg_bin} show interfaces 2>/dev/null'"
|
||||
f"'echo HAS=$(test -f {shlex.quote(conf)} && echo 1 || echo 0); "
|
||||
f"echo IFACES=$({wg_bin} show interfaces 2>/dev/null); "
|
||||
f"echo HANDSHAKE=$({wg_bin} show cascade latest-handshakes 2>/dev/null | awk \"{{print \\$2}}\" | head -1); "
|
||||
f"echo TRANSFER=$({wg_bin} show cascade transfer 2>/dev/null | head -1); "
|
||||
f"ip rule show 2>/dev/null | head -20; "
|
||||
f"ip route show table 200 2>/dev/null | head -10'"
|
||||
)
|
||||
text = out or ''
|
||||
ifaces = []
|
||||
has_conf = 'HAS=1' in text
|
||||
ifaces_line = ''
|
||||
handshake_ts = 0
|
||||
for line in text.splitlines():
|
||||
if line.strip() == 'HAS_CONF':
|
||||
continue
|
||||
ifaces.extend(line.split())
|
||||
up = 'cascade' in ifaces or bool(re.search(r'\bcascade\b', text))
|
||||
if line.startswith('IFACES='):
|
||||
ifaces_line = line.split('=', 1)[1].strip()
|
||||
if line.startswith('HANDSHAKE='):
|
||||
try:
|
||||
handshake_ts = int(line.split('=', 1)[1].strip() or '0')
|
||||
except ValueError:
|
||||
handshake_ts = 0
|
||||
up = 'cascade' in ifaces_line.split()
|
||||
# WireGuard reports unix timestamp; 0 means never
|
||||
handshake_ok = handshake_ts > 0
|
||||
return {
|
||||
'enabled': 'HAS_CONF' in text,
|
||||
'enabled': has_conf,
|
||||
'up': up,
|
||||
'raw': text.strip()[:2000],
|
||||
'handshake': handshake_ok,
|
||||
'handshake_ts': handshake_ts,
|
||||
'raw': text.strip()[:3000],
|
||||
}
|
||||
|
||||
def _vpn_subnet(self, entry_protocol: str, container: str) -> str:
|
||||
def _vpn_subnet(self, entry_protocol: str, container: str, override: str = '') -> str:
|
||||
if override and re.match(r'^\d+\.\d+\.\d+\.\d+/\d+$', override.strip()):
|
||||
return override.strip()
|
||||
conf = self._server_conf(entry_protocol)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} bash -lc "
|
||||
@@ -173,7 +237,14 @@ class CascadeManager:
|
||||
return f"{parts[0]}.{parts[1]}.{parts[2]}.0/24"
|
||||
return '10.8.1.0/24'
|
||||
|
||||
def apply(self, entry_protocol: str, exit_client_config: str, exit_host: str) -> dict:
|
||||
def apply(
|
||||
self,
|
||||
entry_protocol: str,
|
||||
exit_client_config: str,
|
||||
exit_host: str,
|
||||
settings: Optional[dict] = None,
|
||||
) -> dict:
|
||||
opts = normalize_settings(settings)
|
||||
container = self._container_name(entry_protocol)
|
||||
if not container:
|
||||
return {'status': 'error', 'message': 'Unsupported entry protocol'}
|
||||
@@ -186,12 +257,87 @@ class CascadeManager:
|
||||
|
||||
cascade_conf_path = self._cascade_conf(entry_protocol)
|
||||
cascade_up_path = self._cascade_up(entry_protocol)
|
||||
cascade_conf = self.prepare_exit_client_config(exit_client_config, exit_host)
|
||||
cascade_conf = self.prepare_exit_client_config(
|
||||
exit_client_config,
|
||||
exit_host,
|
||||
keep_dns=bool(opts['keep_exit_dns']),
|
||||
allowed_ips=str(opts['allowed_ips']),
|
||||
)
|
||||
endpoint_host = self._extract_endpoint_host(cascade_conf) or exit_host
|
||||
subnet = self._vpn_subnet(entry_protocol, container)
|
||||
subnet = self._vpn_subnet(entry_protocol, container, opts.get('vpn_subnet_override') or '')
|
||||
wg_bin = self._wg_binary(entry_protocol)
|
||||
quick_bin = self._quick_binary(entry_protocol)
|
||||
conf_dir = self._conf_dir(entry_protocol)
|
||||
table_id = int(opts['table_id'])
|
||||
prio = int(opts['rule_priority'])
|
||||
hs_timeout = int(opts['handshake_timeout_sec'])
|
||||
|
||||
pin_block = ''
|
||||
if opts['pin_exit_route']:
|
||||
pin_block = f"""
|
||||
EXIT_IP="$EXIT_HOST"
|
||||
if ! printf '%s' "$EXIT_IP" | grep -Eq '^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$'; then
|
||||
EXIT_IP=$(getent ahostsv4 "$EXIT_HOST" 2>/dev/null | awk '{{print $1; exit}}')
|
||||
if [ -z "$EXIT_IP" ]; then
|
||||
EXIT_IP=$(python3 - <<'PY' 2>/dev/null || true
|
||||
import socket
|
||||
print(socket.gethostbyname("{endpoint_host}"))
|
||||
PY
|
||||
)
|
||||
fi
|
||||
fi
|
||||
GW=$(ip route | awk '/default/ {{print $3; exit}}')
|
||||
DEV=$(ip route | awk '/default/ {{print $5; exit}}')
|
||||
if [ -n "$EXIT_IP" ] && [ -n "$GW" ] && [ -n "$DEV" ]; then
|
||||
ip route replace "$EXIT_IP/32" via "$GW" dev "$DEV" 2>/dev/null || true
|
||||
fi
|
||||
"""
|
||||
|
||||
remove_masq = ''
|
||||
if opts['remove_eth_masquerade']:
|
||||
remove_masq = f"""
|
||||
# Stop leaking VPN clients out of the entry server NIC
|
||||
for ETH in eth0 eth1 eth2 ens3 ens5 enp0s3 enp1s0; do
|
||||
while iptables -t nat -D POSTROUTING -s "$SUBNET" -o "$ETH" -j MASQUERADE 2>/dev/null; do :; done
|
||||
done
|
||||
"""
|
||||
|
||||
forward_block = ''
|
||||
if opts['force_forward']:
|
||||
forward_block = f"""
|
||||
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
|
||||
for SRC_IF in awg0 wg0; do
|
||||
iptables -C FORWARD -i "$SRC_IF" -o "$IFACE" -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$SRC_IF" -o "$IFACE" -j ACCEPT 2>/dev/null || true
|
||||
iptables -C FORWARD -i "$IFACE" -o "$SRC_IF" -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$IFACE" -o "$SRC_IF" -j ACCEPT 2>/dev/null || true
|
||||
done
|
||||
iptables -C FORWARD -i "$IFACE" -m state --state RELATED,ESTABLISHED -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$IFACE" -m state --state RELATED,ESTABLISHED -j ACCEPT
|
||||
"""
|
||||
|
||||
mss_block = ''
|
||||
if opts['mss_clamp']:
|
||||
mss_block = """
|
||||
iptables -t mangle -C FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2>/dev/null \\
|
||||
|| iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
|
||||
"""
|
||||
|
||||
handshake_block = ''
|
||||
if opts['wait_handshake']:
|
||||
handshake_block = f"""
|
||||
OK=0
|
||||
for i in $(seq 1 {hs_timeout}); do
|
||||
HS=$({shlex.quote(wg_bin)} show "$IFACE" latest-handshakes 2>/dev/null | awk '{{print $2}}' | head -1)
|
||||
if [ -n "$HS" ] && [ "$HS" != "0" ]; then OK=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
if [ "$OK" != "1" ]; then
|
||||
echo "CASCADE_NO_HANDSHAKE" >&2
|
||||
echo "Tunnel interface is up but exit peer did not handshake. Check exit server / UDP port / keys." >&2
|
||||
exit 42
|
||||
fi
|
||||
"""
|
||||
|
||||
up_script = f"""#!/bin/bash
|
||||
{CASCADE_MARKER}
|
||||
@@ -201,35 +347,29 @@ QUICK={shlex.quote(quick_bin)}
|
||||
SUBNET={shlex.quote(subnet)}
|
||||
EXIT_HOST={shlex.quote(endpoint_host)}
|
||||
IFACE=cascade
|
||||
TABLE={table_id}
|
||||
PRIO={prio}
|
||||
|
||||
"$QUICK" down "$CONF" 2>/dev/null || true
|
||||
ip link delete "$IFACE" 2>/dev/null || true
|
||||
ip rule del from "$SUBNET" table "$TABLE" 2>/dev/null || true
|
||||
ip route flush table "$TABLE" 2>/dev/null || true
|
||||
|
||||
# Resolve hostname to IP if needed (pin route must use IP)
|
||||
EXIT_IP="$EXIT_HOST"
|
||||
if ! printf '%s' "$EXIT_IP" | grep -Eq '^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$'; then
|
||||
EXIT_IP=$(getent ahostsv4 "$EXIT_HOST" 2>/dev/null | awk '{{print $1; exit}}')
|
||||
fi
|
||||
GW=$(ip route | awk '/default/ {{print $3; exit}}')
|
||||
DEV=$(ip route | awk '/default/ {{print $5; exit}}')
|
||||
if [ -n "$EXIT_IP" ] && [ -n "$GW" ] && [ -n "$DEV" ]; then
|
||||
ip route replace "$EXIT_IP/32" via "$GW" dev "$DEV" 2>/dev/null || true
|
||||
fi
|
||||
{pin_block}
|
||||
|
||||
"$QUICK" up "$CONF"
|
||||
|
||||
ip route replace default dev "$IFACE" table 200 2>/dev/null || ip route add default dev "$IFACE" table 200
|
||||
ip rule del from "$SUBNET" table 200 2>/dev/null || true
|
||||
ip rule add from "$SUBNET" table 200 priority 100
|
||||
# Source-based routing: VPN clients go through cascade iface
|
||||
ip route replace default dev "$IFACE" table "$TABLE" 2>/dev/null || ip route add default dev "$IFACE" table "$TABLE"
|
||||
ip rule del from "$SUBNET" table "$TABLE" 2>/dev/null || true
|
||||
ip rule add from "$SUBNET" table "$TABLE" priority "$PRIO"
|
||||
|
||||
for SRC_IF in awg0 wg0; do
|
||||
iptables -C FORWARD -i "$SRC_IF" -o "$IFACE" -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$SRC_IF" -o "$IFACE" -j ACCEPT 2>/dev/null || true
|
||||
done
|
||||
iptables -C FORWARD -i "$IFACE" -m state --state RELATED,ESTABLISHED -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$IFACE" -m state --state RELATED,ESTABLISHED -j ACCEPT
|
||||
{remove_masq}
|
||||
{forward_block}
|
||||
iptables -t nat -C POSTROUTING -s "$SUBNET" -o "$IFACE" -j MASQUERADE 2>/dev/null \\
|
||||
|| iptables -t nat -A POSTROUTING -s "$SUBNET" -o "$IFACE" -j MASQUERADE
|
||||
{mss_block}
|
||||
{handshake_block}
|
||||
|
||||
echo CASCADE_UP_OK
|
||||
"""
|
||||
@@ -249,12 +389,21 @@ echo CASCADE_UP_OK
|
||||
|
||||
out, err, code = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} bash {shlex.quote(cascade_up_path)}",
|
||||
timeout=90,
|
||||
timeout=max(90, hs_timeout + 40),
|
||||
)
|
||||
combined = ((out or '') + '\n' + (err or '')).strip()
|
||||
if code != 0 or 'CASCADE_UP_OK' not in (out or ''):
|
||||
msg = combined
|
||||
if 'CASCADE_NO_HANDSHAKE' in combined:
|
||||
msg = (
|
||||
'Туннель к серверу выхода поднят, но handshake не прошёл. '
|
||||
'Проверьте, что на выходе открыт UDP-порт, протокол совпадает, '
|
||||
'и входной сервер может достучаться до IP выхода.'
|
||||
)
|
||||
return {
|
||||
'status': 'error',
|
||||
'message': (err or out or 'Failed to bring cascade interface up').strip()[:800],
|
||||
'message': (msg or 'Failed to bring cascade interface up').strip()[:900],
|
||||
'log': combined[:2000],
|
||||
}
|
||||
|
||||
st = self.status(entry_protocol)
|
||||
@@ -264,7 +413,10 @@ echo CASCADE_UP_OK
|
||||
'endpoint': endpoint_host,
|
||||
'container': container,
|
||||
'up': bool(st.get('up')),
|
||||
'handshake': bool(st.get('handshake')),
|
||||
'settings': opts,
|
||||
'applied_at': datetime.now().isoformat(timespec='seconds'),
|
||||
'diagnostics': st.get('raw', '')[:1500],
|
||||
}
|
||||
|
||||
def _ensure_start_hook(self, container: str, cascade_up_path: str) -> None:
|
||||
@@ -285,24 +437,26 @@ printf '%s\\n' 'if [ -x {cascade_up_path} ]; then bash {cascade_up_path} || true
|
||||
)
|
||||
self.ssh.run_command('rm -f /tmp/_amnz_cascade_hook.sh')
|
||||
|
||||
def disable(self, entry_protocol: str) -> dict:
|
||||
def disable(self, entry_protocol: str, settings: Optional[dict] = None) -> dict:
|
||||
opts = normalize_settings(settings)
|
||||
container = self._container_name(entry_protocol)
|
||||
if not container:
|
||||
return {'status': 'error', 'message': 'Unsupported entry protocol'}
|
||||
conf = self._cascade_conf(entry_protocol)
|
||||
up = self._cascade_up(entry_protocol)
|
||||
quick_bin = self._quick_binary(entry_protocol)
|
||||
# Avoid nested quotes issues: upload a small script
|
||||
table_id = int(opts['table_id'])
|
||||
script = f"""#!/bin/bash
|
||||
set +e
|
||||
QUICK={shlex.quote(quick_bin)}
|
||||
CONF={shlex.quote(conf)}
|
||||
UP={shlex.quote(up)}
|
||||
TABLE={table_id}
|
||||
"$QUICK" down "$CONF" 2>/dev/null
|
||||
ip link delete cascade 2>/dev/null
|
||||
ip rule del table 200 2>/dev/null
|
||||
ip rule del table 200 2>/dev/null
|
||||
ip route flush table 200 2>/dev/null
|
||||
ip rule del table "$TABLE" 2>/dev/null
|
||||
ip rule del table "$TABLE" 2>/dev/null
|
||||
ip route flush table "$TABLE" 2>/dev/null
|
||||
rm -f "$CONF" "$UP"
|
||||
echo CASCADE_DOWN_OK
|
||||
"""
|
||||
|
||||
+150
-3
@@ -522,6 +522,84 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-hint" style="margin-bottom:var(--space-md);">{{ _('cascade_hint') }}</div>
|
||||
|
||||
<details id="cascadeSettingsPanel" open style="margin-bottom:var(--space-md); border:1px solid var(--border); border-radius:var(--radius-md); padding:var(--space-sm) var(--space-md);">
|
||||
<summary style="cursor:pointer; font-weight:600; margin-bottom:var(--space-sm);">{{ _('cascade_settings_title') }}</summary>
|
||||
<p class="form-hint" style="margin:0 0 var(--space-md);">{{ _('cascade_settings_desc') }}</p>
|
||||
<div class="grid" style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-sm) var(--space-md);">
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadePinExitRoute" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_pin_exit') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_pin_exit_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeRemoveEthMasq" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_remove_eth_masq') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_remove_eth_masq_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeForceForward" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_force_forward') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_force_forward_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeMssClamp" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_mss_clamp') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_mss_clamp_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeWaitHandshake" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_wait_handshake') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_wait_handshake_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeKeepExitDns">
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_keep_dns') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_keep_dns_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="grid" style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:var(--space-md); margin-top:var(--space-md);">
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeHandshakeTimeout">{{ _('cascade_opt_handshake_timeout') }}</label>
|
||||
<input type="number" class="form-input" id="cascadeHandshakeTimeout" min="5" max="120" value="25">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeTableId">{{ _('cascade_opt_table_id') }}</label>
|
||||
<input type="number" class="form-input" id="cascadeTableId" min="1" max="252" value="200">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeRulePriority">{{ _('cascade_opt_rule_priority') }}</label>
|
||||
<input type="number" class="form-input" id="cascadeRulePriority" min="1" max="32765" value="100">
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid" style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-md); margin-top:var(--space-md);">
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeAllowedIps">{{ _('cascade_opt_allowed_ips') }}</label>
|
||||
<input type="text" class="form-input" id="cascadeAllowedIps" value="0.0.0.0/0, ::/0">
|
||||
<span class="form-hint">{{ _('cascade_opt_allowed_ips_hint') }}</span>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeVpnSubnet">{{ _('cascade_opt_vpn_subnet') }}</label>
|
||||
<input type="text" class="form-input" id="cascadeVpnSubnet" placeholder="10.8.1.0/24" value="">
|
||||
<span class="form-hint">{{ _('cascade_opt_vpn_subnet_hint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div id="cascadeDiagBox" class="hidden" style="margin-bottom:var(--space-md); padding:var(--space-sm) var(--space-md); background:var(--bg-muted, rgba(0,0,0,.04)); border-radius:var(--radius-md); font-family:ui-monospace,monospace; font-size:12px; white-space:pre-wrap; max-height:160px; overflow:auto;"></div>
|
||||
|
||||
<div class="flex gap-sm" style="flex-wrap:wrap;">
|
||||
<button type="button" class="btn btn-primary" id="cascadeEnableBtn" onclick="setupCascade(true)">
|
||||
{{ _('cascade_enable') }}
|
||||
@@ -2703,15 +2781,78 @@
|
||||
if (dis) dis.disabled = !!on;
|
||||
}
|
||||
|
||||
function cascadeBool(id, fallback) {
|
||||
const el = document.getElementById(id);
|
||||
return el ? !!el.checked : !!fallback;
|
||||
}
|
||||
|
||||
function cascadeNum(id, fallback) {
|
||||
const el = document.getElementById(id);
|
||||
const n = el ? parseInt(el.value, 10) : NaN;
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
function collectCascadeSettings() {
|
||||
return {
|
||||
pin_exit_route: cascadeBool('cascadePinExitRoute', true),
|
||||
remove_eth_masquerade: cascadeBool('cascadeRemoveEthMasq', true),
|
||||
force_forward: cascadeBool('cascadeForceForward', true),
|
||||
mss_clamp: cascadeBool('cascadeMssClamp', true),
|
||||
wait_handshake: cascadeBool('cascadeWaitHandshake', true),
|
||||
keep_exit_dns: cascadeBool('cascadeKeepExitDns', false),
|
||||
handshake_timeout_sec: cascadeNum('cascadeHandshakeTimeout', 25),
|
||||
table_id: cascadeNum('cascadeTableId', 200),
|
||||
rule_priority: cascadeNum('cascadeRulePriority', 100),
|
||||
allowed_ips: (document.getElementById('cascadeAllowedIps') || {}).value || '0.0.0.0/0, ::/0',
|
||||
vpn_subnet_override: (document.getElementById('cascadeVpnSubnet') || {}).value || '',
|
||||
};
|
||||
}
|
||||
|
||||
function applyCascadeSettingsToForm(settings, defaults) {
|
||||
const s = Object.assign({}, defaults || {}, settings || {});
|
||||
const setCheck = (id, val) => { const el = document.getElementById(id); if (el) el.checked = !!val; };
|
||||
const setVal = (id, val) => { const el = document.getElementById(id); if (el && val !== undefined && val !== null) el.value = val; };
|
||||
setCheck('cascadePinExitRoute', s.pin_exit_route !== false);
|
||||
setCheck('cascadeRemoveEthMasq', s.remove_eth_masquerade !== false);
|
||||
setCheck('cascadeForceForward', s.force_forward !== false);
|
||||
setCheck('cascadeMssClamp', s.mss_clamp !== false);
|
||||
setCheck('cascadeWaitHandshake', s.wait_handshake !== false);
|
||||
setCheck('cascadeKeepExitDns', !!s.keep_exit_dns);
|
||||
setVal('cascadeHandshakeTimeout', s.handshake_timeout_sec ?? 25);
|
||||
setVal('cascadeTableId', s.table_id ?? 200);
|
||||
setVal('cascadeRulePriority', s.rule_priority ?? 100);
|
||||
setVal('cascadeAllowedIps', s.allowed_ips || '0.0.0.0/0, ::/0');
|
||||
setVal('cascadeVpnSubnet', s.vpn_subnet_override || '');
|
||||
}
|
||||
|
||||
function updateCascadeDiag(cascade, live) {
|
||||
const box = document.getElementById('cascadeDiagBox');
|
||||
if (!box) return;
|
||||
const parts = [];
|
||||
if (cascade && cascade.enabled) {
|
||||
parts.push('handshake: ' + ((live && live.handshake) || cascade.handshake ? 'ok' : 'NONE'));
|
||||
if (cascade.subnet || (live && live.raw)) { /* keep */ }
|
||||
if (cascade.diagnostics) parts.push(String(cascade.diagnostics).trim());
|
||||
else if (live && live.raw) parts.push(String(live.raw).trim());
|
||||
if (cascade.last_error) parts.push('error: ' + cascade.last_error);
|
||||
}
|
||||
const text = parts.filter(Boolean).join('\n\n');
|
||||
box.textContent = text;
|
||||
box.classList.toggle('hidden', !text);
|
||||
}
|
||||
|
||||
function updateCascadeBadge(cascade, live) {
|
||||
const badge = document.getElementById('cascadeStatusBadge');
|
||||
if (!badge) return;
|
||||
const enabled = !!(cascade && cascade.enabled);
|
||||
const up = !!(live && live.up);
|
||||
badge.className = 'badge ' + (enabled && up ? 'badge-success' : (enabled ? 'badge-warn' : 'badge-warn'));
|
||||
const hs = !!(live && live.handshake) || !!(cascade && cascade.handshake);
|
||||
badge.className = 'badge ' + (enabled && up && hs ? 'badge-success' : (enabled ? 'badge-warn' : 'badge-warn'));
|
||||
if (!enabled) badge.textContent = _('cascade_off');
|
||||
else if (up) badge.textContent = _('cascade_on');
|
||||
else if (up && hs) badge.textContent = _('cascade_on');
|
||||
else if (up && !hs) badge.textContent = _('cascade_no_handshake');
|
||||
else badge.textContent = _('cascade_configured_down');
|
||||
updateCascadeDiag(cascade, live);
|
||||
}
|
||||
|
||||
async function loadCascadeStatus() {
|
||||
@@ -2729,6 +2870,7 @@
|
||||
exitProto.value = c.exit_protocol;
|
||||
}
|
||||
}
|
||||
applyCascadeSettingsToForm(c.settings || {}, res.defaults || {});
|
||||
updateCascadeBadge(c, res.live || {});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@@ -2749,13 +2891,18 @@
|
||||
setCascadeBusy(true, enable ? _('cascade_working') : _('cascade_disabling'));
|
||||
showToast(enable ? _('cascade_working') : _('cascade_disabling'), 'info');
|
||||
try {
|
||||
const settings = collectCascadeSettings();
|
||||
const res = await apiCall(`/api/servers/${SERVER_ID}/cascade/setup`, 'POST', {
|
||||
enabled: !!enable,
|
||||
entry_protocol: entryProtocol,
|
||||
exit_server_id: parseInt(exitServerId || '0', 10),
|
||||
exit_protocol: exitProtocol,
|
||||
...settings,
|
||||
});
|
||||
updateCascadeBadge(res.cascade || {}, {
|
||||
up: !!(res.cascade && res.cascade.up),
|
||||
handshake: !!(res.cascade && res.cascade.handshake),
|
||||
});
|
||||
updateCascadeBadge(res.cascade || {}, { up: !!(res.cascade && res.cascade.up) });
|
||||
showToast(enable ? _('cascade_enabled') : _('cascade_disabled'), 'success');
|
||||
await loadCascadeStatus();
|
||||
} catch (err) {
|
||||
|
||||
+23
-1
@@ -538,5 +538,27 @@
|
||||
"cascade_configured_down": "Configured, tunnel down",
|
||||
"cascade_exit_required": "Select an exit server",
|
||||
"cascade_enable_confirm": "Enable cascade? A service client will be created on the exit server and a tunnel will be set up on this entry server.",
|
||||
"cascade_disable_confirm": "Disable cascade on this server?"
|
||||
"cascade_disable_confirm": "Disable cascade on this server?",
|
||||
"cascade_no_handshake": "Up, no handshake",
|
||||
"cascade_settings_title": "Cascade settings (per step)",
|
||||
"cascade_settings_desc": "If pages spin forever with no internet — keep all options on and click Enable cascade again.",
|
||||
"cascade_opt_pin_exit": "Pin route to exit server",
|
||||
"cascade_opt_pin_exit_hint": "Keeps the exit tunnel from looping through the VPN itself.",
|
||||
"cascade_opt_remove_eth_masq": "Remove client NAT on eth0",
|
||||
"cascade_opt_remove_eth_masq_hint": "Clients must not egress directly from the entry server.",
|
||||
"cascade_opt_force_forward": "Force FORWARD between interfaces",
|
||||
"cascade_opt_force_forward_hint": "Client traffic → cascade → exit.",
|
||||
"cascade_opt_mss_clamp": "TCP MSS clamp",
|
||||
"cascade_opt_mss_clamp_hint": "Fixes endless page loads on double VPN.",
|
||||
"cascade_opt_wait_handshake": "Wait for exit handshake",
|
||||
"cascade_opt_wait_handshake_hint": "Do not mark cascade active if the exit peer never answers.",
|
||||
"cascade_opt_keep_dns": "Keep DNS from exit config",
|
||||
"cascade_opt_keep_dns_hint": "Usually off — the client sets DNS itself.",
|
||||
"cascade_opt_handshake_timeout": "Handshake timeout (sec)",
|
||||
"cascade_opt_table_id": "Routing table id",
|
||||
"cascade_opt_rule_priority": "ip rule priority",
|
||||
"cascade_opt_allowed_ips": "AllowedIPs for entry→exit tunnel",
|
||||
"cascade_opt_allowed_ips_hint": "Usually 0.0.0.0/0, ::/0",
|
||||
"cascade_opt_vpn_subnet": "Client subnet override",
|
||||
"cascade_opt_vpn_subnet_hint": "Empty = auto-detect from server Address"
|
||||
}
|
||||
|
||||
+23
-1
@@ -538,5 +538,27 @@
|
||||
"cascade_configured_down": "Настроен, туннель вниз",
|
||||
"cascade_exit_required": "Выберите сервер выхода",
|
||||
"cascade_enable_confirm": "Включить каскад? На выходном сервере будет создан служебный клиент, а на этом — туннель к нему.",
|
||||
"cascade_disable_confirm": "Отключить каскад на этом сервере?"
|
||||
"cascade_disable_confirm": "Отключить каскад на этом сервере?",
|
||||
"cascade_no_handshake": "Туннель вверх, нет handshake",
|
||||
"cascade_settings_title": "Настройки каскада (по шагам)",
|
||||
"cascade_settings_desc": "Если страницы «крутятся», а интернета нет — оставьте все галочки включёнными и снова нажмите «Включить каскад».",
|
||||
"cascade_opt_pin_exit": "Закрепить маршрут к серверу выхода",
|
||||
"cascade_opt_pin_exit_hint": "Чтобы туннель к выходу не ушёл в петлю через сам VPN.",
|
||||
"cascade_opt_remove_eth_masq": "Убрать NAT клиентов в eth0",
|
||||
"cascade_opt_remove_eth_masq_hint": "Клиенты не должны выходить в интернет напрямую с входного сервера.",
|
||||
"cascade_opt_force_forward": "Разрешить FORWARD между интерфейсами",
|
||||
"cascade_opt_force_forward_hint": "Трафик клиентов → cascade → выход.",
|
||||
"cascade_opt_mss_clamp": "TCP MSS clamp",
|
||||
"cascade_opt_mss_clamp_hint": "Чинит «вечную загрузку» сайтов при двойном VPN.",
|
||||
"cascade_opt_wait_handshake": "Ждать handshake с выходом",
|
||||
"cascade_opt_wait_handshake_hint": "Не помечать каскад «активным», если выход не отвечает.",
|
||||
"cascade_opt_keep_dns": "Оставить DNS из конфига выхода",
|
||||
"cascade_opt_keep_dns_hint": "Обычно выключено — DNS берёт клиент сам.",
|
||||
"cascade_opt_handshake_timeout": "Таймаут handshake (сек)",
|
||||
"cascade_opt_table_id": "Таблица маршрутов",
|
||||
"cascade_opt_rule_priority": "Приоритет ip rule",
|
||||
"cascade_opt_allowed_ips": "AllowedIPs туннеля вход→выход",
|
||||
"cascade_opt_allowed_ips_hint": "Обычно 0.0.0.0/0, ::/0",
|
||||
"cascade_opt_vpn_subnet": "Подсеть клиентов (override)",
|
||||
"cascade_opt_vpn_subnet_hint": "Пусто = определить автоматически из Address сервера"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user