Archived
1.0.2 - fix network settings, permissions and branding
Wydanie WGTools-Extended / release (push) Successful in 14s
Wydanie WGTools-Extended / release (push) Successful in 14s
This commit is contained in:
1 parent
9c23169339
commit
aadc19341d
18 files changed
+241
-80
No files matched your search
+91
-17
@@ -28,6 +28,7 @@ from typing import Any
|
||||
|
||||
ALLOWED_ACTIONS = {"snapshot", "interfaces_list", "interface_meta_set", "interface_delete", "metrics_sample", "metrics_history", "diagnostics", "network_trace", "wireguard_start", "wireguard_stop", "wireguard_restart", "install_wireguard", "create_server", "create_client", "update_client", "delete_client", "rotate_client_credentials", "expire_clients", "client_config", "group_create", "group_update", "group_delete", "raw_config_get", "raw_config_apply", "server_settings_apply", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete", "migration_backup_create", "migration_restore", "update_check", "update_notice", "update_status", "update_schedule", "update_apply", "traffic_reset", "https_status", "https_ports", "https_issue", "https_enable", "https_disable", "https_switch_commit"}
|
||||
ALLOWED_ACTIONS.update({"extended_snat_get", "extended_snat_apply"})
|
||||
ALLOWED_ACTIONS.add("extended_host_ips")
|
||||
ALLOWED_ACTIONS.update({"extended_listen_get", "extended_listen_apply"})
|
||||
ALLOWED_ACTIONS.update({"extended_ip_groups_get", "extended_ip_groups_set", "extended_forward_get", "extended_forward_add", "extended_forward_delete"})
|
||||
ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"})
|
||||
@@ -2121,6 +2122,7 @@ def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
raise RuntimeError(f"{config_path} already exists; WGTools will not overwrite an existing server configuration")
|
||||
|
||||
settings = validate_server_payload(iface, payload)
|
||||
source_groups = _prepare_network_sources(iface, str(payload.get("forward_sources") or "")) if payload.get("forward_sources") else None
|
||||
private_key = generate_private_key()
|
||||
public_key = private_to_public(private_key)
|
||||
network = settings["network"]
|
||||
@@ -2173,6 +2175,10 @@ def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
lines.extend(f"PostDown = {cmd}" for cmd in post_down)
|
||||
lines.append("")
|
||||
config_text = "\n".join(lines)
|
||||
if payload.get("listen_address") or payload.get("listen_interface"):
|
||||
config_text = extended_listen_apply(iface, {"address": payload.get("listen_address"), "interface": payload.get("listen_interface")}, text_override=config_text, prepare_only=True)["content"]
|
||||
if payload.get("snat_address"):
|
||||
config_text = extended_snat_apply(iface, {"address": payload.get("snat_address"), "uplink": uplink}, text_override=config_text, prepare_only=True)["content"]
|
||||
|
||||
WG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
os.chmod(WG_DIR, 0o700)
|
||||
@@ -2204,6 +2210,15 @@ def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not dump.get("running"):
|
||||
raise RuntimeError("wg-quick started without an error, but the WireGuard interface is not visible in wg show")
|
||||
|
||||
if source_groups is not None:
|
||||
try:
|
||||
_save_extended_groups(source_groups)
|
||||
except Exception as exc:
|
||||
run([systemctl, "disable", "--now", f"wg-quick@{iface}.service"], timeout=30)
|
||||
failed_path = WG_DIR / f"{iface}.failed-{time.strftime('%Y%m%d-%H%M%S')}.conf"
|
||||
os.replace(config_path, failed_path)
|
||||
raise RuntimeError(f"Nie zapisano adresów do przekierowań; interfejs zatrzymano, konfigurację zachowano w {failed_path}: {exc}") from exc
|
||||
|
||||
interface_meta_set(iface, {"display_name": str(payload.get("display_name") or iface)})
|
||||
|
||||
return {
|
||||
@@ -4335,7 +4350,54 @@ def _extended_configured() -> set[str]:
|
||||
|
||||
|
||||
def _extended_allowed(groups: dict[str, Any], iface: str) -> set[str]:
|
||||
return {addr for group in groups.values() if iface in group.get("interfaces", []) for addr in group.get("addresses", [])}
|
||||
allowed: set[str] = set()
|
||||
host_ips = None
|
||||
for group in groups.values():
|
||||
if iface not in group.get("interfaces", []):
|
||||
continue
|
||||
if "sources" in group:
|
||||
if host_ips is None:
|
||||
host_ips = _extended_host_ips()
|
||||
allowed.update(ip for ip, dev in host_ips.items() if ip in group["sources"] or dev in group["sources"])
|
||||
else:
|
||||
allowed.update(group.get("addresses", []))
|
||||
return allowed
|
||||
|
||||
|
||||
def _network_sources_name(iface: str) -> str:
|
||||
return f"_wgext_network_{iface}"
|
||||
|
||||
|
||||
def _prepare_network_sources(iface: str, text: str) -> dict[str, Any]:
|
||||
sources = list(dict.fromkeys(item.strip() for item in text.split(',') if item.strip()))
|
||||
if len(sources) > 256:
|
||||
raise ValueError("Zbyt wiele adresów lub interfejsów")
|
||||
host = _extended_host_ips()
|
||||
for source in sources:
|
||||
if source not in host and source not in host.values():
|
||||
raise ValueError(f"Adres lub interfejs {source} nie ma przypisanego IPv4 na serwerze")
|
||||
groups = _extended_groups()
|
||||
key = _network_sources_name(iface)
|
||||
if sources:
|
||||
groups[key] = {"addresses": sorted(ip for ip, dev in host.items() if ip in sources or dev in sources), "interfaces": [iface], "sources": sources}
|
||||
else:
|
||||
groups.pop(key, None)
|
||||
if (WG_DIR / f"{iface}.conf").is_file():
|
||||
for row in _extended_forwards(iface):
|
||||
if row["public_ip"] not in _extended_allowed(groups, iface):
|
||||
raise ValueError("Najpierw usuń przekierowania korzystające z odbieranego adresu")
|
||||
return groups
|
||||
|
||||
|
||||
def _save_extended_groups(groups: dict[str, Any]) -> None:
|
||||
EXT_IP_GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = EXT_IP_GROUPS_PATH.with_name(f".{EXT_IP_GROUPS_PATH.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
temp.write_text(json.dumps(groups, ensure_ascii=False), encoding="utf-8")
|
||||
os.chmod(temp, 0o600)
|
||||
os.replace(temp, EXT_IP_GROUPS_PATH)
|
||||
finally:
|
||||
temp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _extended_host_ips() -> dict[str, str]:
|
||||
@@ -4401,6 +4463,8 @@ def extended_ip_groups_set(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
name = str(payload.get("name") or "").strip()
|
||||
if not re.fullmatch(r"[A-Za-z0-9_. -]{1,64}", name):
|
||||
raise ValueError("Nieprawidłowa nazwa grupy")
|
||||
if name.startswith('_wgext_network_'):
|
||||
raise ValueError("Tą grupą zarządza formularz sieci")
|
||||
groups = _extended_groups()
|
||||
if payload.get("delete"):
|
||||
if name not in groups:
|
||||
@@ -4426,14 +4490,7 @@ def extended_ip_groups_set(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
for row in _extended_forwards(iface):
|
||||
if row["public_ip"] not in _extended_allowed(groups, iface):
|
||||
raise ValueError(f"Zmiana odebrałaby adres używany przez przekierowanie w {iface}; usuń najpierw przekierowanie")
|
||||
EXT_IP_GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = EXT_IP_GROUPS_PATH.with_name(f".{EXT_IP_GROUPS_PATH.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
temp.write_text(json.dumps(groups, ensure_ascii=False), encoding="utf-8")
|
||||
os.chmod(temp, 0o600)
|
||||
os.replace(temp, EXT_IP_GROUPS_PATH)
|
||||
finally:
|
||||
temp.unlink(missing_ok=True)
|
||||
_save_extended_groups(groups)
|
||||
return {"ok": True, "groups": groups}
|
||||
|
||||
|
||||
@@ -4544,9 +4601,9 @@ def extended_listen_get(iface: str) -> dict[str, Any]:
|
||||
return {"ok": True, "address": match.group(1), "interface": match.group(2)}
|
||||
|
||||
|
||||
def extended_listen_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def extended_listen_apply(iface: str, payload: dict[str, Any], *, text_override: str | None = None, prepare_only: bool = False) -> dict[str, Any]:
|
||||
require_valid_iface(iface)
|
||||
text = read_config_text(iface)
|
||||
text = text_override if text_override is not None else read_config_text(iface)
|
||||
cfg = parse_config(text, iface)
|
||||
address = str(payload.get("address") or "").strip()
|
||||
device = str(payload.get("interface") or "").strip()
|
||||
@@ -4586,14 +4643,15 @@ def extended_listen_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]
|
||||
section.extend([metadata + f"address={address} interface={device}",
|
||||
f"PostUp = iptables -w -I INPUT 1 {drop4} && ip6tables -w -I INPUT 1 {drop6} && iptables -w -I INPUT 1 {allow4} || {{ {cleanup}; false; }}",
|
||||
f"PostDown = {cleanup}"])
|
||||
result = raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"})
|
||||
new_text = "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"
|
||||
result = {"ok": True, "content": new_text} if prepare_only else raw_config_apply(iface, {"content": new_text})
|
||||
result.update({"address": address, "interface": device})
|
||||
return result
|
||||
|
||||
|
||||
def extended_snat_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def extended_snat_apply(iface: str, payload: dict[str, Any], *, text_override: str | None = None, prepare_only: bool = False) -> dict[str, Any]:
|
||||
require_valid_iface(iface)
|
||||
text = read_config_text(iface)
|
||||
text = text_override if text_override is not None else read_config_text(iface)
|
||||
cfg = parse_config(text, iface)
|
||||
address = str(payload.get("address") or "").strip()
|
||||
uplink = str(payload.get("uplink") or "").strip()
|
||||
@@ -4626,7 +4684,7 @@ def extended_snat_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
rule = f"-s {network} -o {uplink} -m comment --comment {marker} -j SNAT --to-source {address}"
|
||||
section.extend([f"PostUp = iptables -t nat -I POSTROUTING 1 {rule}", f"PostDown = iptables -t nat -D POSTROUTING {rule}"])
|
||||
new_text = "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"
|
||||
result = raw_config_apply(iface, {"content": new_text})
|
||||
result = {"ok": True, "content": new_text} if prepare_only else raw_config_apply(iface, {"content": new_text})
|
||||
result.update({"address": address, "uplink": uplink if address else ""})
|
||||
return result
|
||||
|
||||
@@ -4641,15 +4699,16 @@ def server_settings_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]
|
||||
|
||||
old_text = read_config_text(iface)
|
||||
old_cfg = parse_config(old_text, iface)
|
||||
source_groups = _prepare_network_sources(iface, str(payload.get("forward_sources") or "")) if "forward_sources" in payload else None
|
||||
normalized = dict(payload)
|
||||
normalized["forward_from_vpn"] = bool(payload.get("forward_from_vpn", True))
|
||||
normalized["forward_to_vpn"] = bool(payload.get("forward_to_vpn", True))
|
||||
settings = validate_server_payload(iface, normalized)
|
||||
listen = extended_listen_get(iface)
|
||||
if (listen["address"] or listen["interface"]) and settings["listen_port"] != (old_cfg.get("interface") or {}).get("listen_port"):
|
||||
if "listen_address" not in payload and (listen["address"] or listen["interface"]) and settings["listen_port"] != (old_cfg.get("interface") or {}).get("listen_port"):
|
||||
raise ValueError("Przed zmianą portu wyłącz ograniczenie nasłuchiwania i ustaw je ponownie")
|
||||
snat = extended_snat_get(iface)
|
||||
if snat["address"] and (settings["network"] != str((old_cfg.get("detected") or {}).get("vpn_network") or "") or settings["uplink_interface"] != snat["uplink"]):
|
||||
if "snat_address" not in payload and snat["address"] and (settings["network"] != str((old_cfg.get("detected") or {}).get("vpn_network") or "") or settings["uplink_interface"] != snat["uplink"]):
|
||||
raise ValueError("Przed zmianą sieci VPN lub interfejsu wyjściowego usuń podstawowy adres SNAT i ustaw go ponownie po zapisaniu zmian")
|
||||
settings["forward_from_vpn"] = normalized["forward_from_vpn"]
|
||||
settings["forward_to_vpn"] = normalized["forward_to_vpn"]
|
||||
@@ -4710,7 +4769,20 @@ def server_settings_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]
|
||||
new_lines = [*prefix, *new_section, *suffix]
|
||||
new_text = "\n".join(new_lines).rstrip() + "\n"
|
||||
new_text = sync_managed_client_policies(new_text, iface)
|
||||
if "listen_address" in payload:
|
||||
new_text = extended_listen_apply(iface, {"address": payload.get("listen_address"), "interface": payload.get("listen_interface")}, text_override=new_text, prepare_only=True)["content"]
|
||||
if "snat_address" in payload:
|
||||
new_text = extended_snat_apply(iface, {"address": payload.get("snat_address"), "uplink": settings["uplink_interface"]}, text_override=new_text, prepare_only=True)["content"]
|
||||
result = raw_config_apply(iface, {"content": new_text})
|
||||
if source_groups is not None:
|
||||
try:
|
||||
_save_extended_groups(source_groups)
|
||||
except Exception as exc:
|
||||
try:
|
||||
raw_config_apply(iface, {"content": old_text})
|
||||
except Exception as rollback:
|
||||
raise RuntimeError(f"Nie zapisano adresów do przekierowań i nie udało się przywrócić konfiguracji: {rollback}") from exc
|
||||
raise RuntimeError(f"Nie zapisano adresów do przekierowań; przywrócono poprzednią konfigurację: {exc}") from exc
|
||||
|
||||
sysctl_file = Path("/etc/sysctl.d/99-wgtools-wireguard.conf")
|
||||
sysctl_value = "1" if settings["ip_forwarding"] else "0"
|
||||
@@ -6642,6 +6714,8 @@ def main() -> int:
|
||||
result = locked_call(lambda: server_settings_apply(iface, payload))
|
||||
elif action == "extended_snat_get":
|
||||
result = extended_snat_get(iface)
|
||||
elif action == "extended_host_ips":
|
||||
result = {"ok": True, "addresses": _extended_host_ips()}
|
||||
elif action == "extended_snat_apply":
|
||||
payload = read_json_stdin()
|
||||
result = locked_call(lambda: extended_snat_apply(iface, payload))
|
||||
|
||||
Reference in new issue
Block a user