Archived
1.0.4 - ograniczenia IP i edycja przekierowań
Wydanie WGTools-Extended / release (push) Successful in 15s
Wydanie WGTools-Extended / release (push) Successful in 15s
This commit is contained in:
1 parent
3841e93e32
commit
6e7eaa9282
13 files changed
+115
-17
No files matched your search
+43
-6
@@ -31,6 +31,7 @@ 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.add("extended_forward_update")
|
||||
ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"})
|
||||
ALLOWED_IFACE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,15}$")
|
||||
INTERNAL_INTERFACE_PREFIXES = ("wgrly", "wgnode")
|
||||
@@ -4449,6 +4450,10 @@ def _extended_forwards(iface: str) -> list[dict[str, Any]]:
|
||||
raise ValueError()
|
||||
if row["protocol"] not in {"tcp", "udp", "both"} or not ALLOWED_IFACE_RE.fullmatch(row["device"]) or row["device"].startswith('-'):
|
||||
raise ValueError()
|
||||
sources = row.get("allowed_sources", [])
|
||||
if not isinstance(sources, list) or len(sources) > 32:
|
||||
raise ValueError()
|
||||
row["allowed_sources"] = sorted({str(ipaddress.IPv4Address(value)) for value in sources})
|
||||
except (KeyError, ValueError, TypeError) as exc:
|
||||
raise ValueError(f"Nieprawidłowy wpis przekierowania w {iface}") from exc
|
||||
result.append(row)
|
||||
@@ -4500,6 +4505,9 @@ def extended_forward_get(iface: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
complexity = sum((len(row.get('allowed_sources', [])) or 1) * (2 if row['protocol'] == 'both' else 1) for row in rows)
|
||||
if complexity > 100:
|
||||
raise ValueError("Zbyt wiele adresów źródłowych w przekierowaniach tej sieci")
|
||||
prefix, section, suffix = _interface_section_parts(read_config_text(iface))
|
||||
marker = f"wgext-forward-{iface}"
|
||||
section = [line for line in section if not (line.strip().startswith("# WGEXT-FORWARD ") or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))]
|
||||
@@ -4510,9 +4518,19 @@ def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str
|
||||
for proto in (["tcp", "udp"] if row["protocol"] == "both" else [row["protocol"]]):
|
||||
tag = f"{marker}-{row['id']}-{proto}"
|
||||
nat = f"-i {row['device']} -d {row['public_ip']} -p {proto} --dport {row['public_port']} -m comment --comment {tag}-nat -j DNAT --to-destination {row['target_ip']}:{row['target_port']}"
|
||||
forward = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m comment --comment {tag}-in -j ACCEPT"
|
||||
forward_match = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}"
|
||||
reply = f"-i {iface} -o {row['device']} -s {row['target_ip']} -p {proto} --sport {row['target_port']} -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment {tag}-out -j ACCEPT"
|
||||
for table, chain, rule in [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', forward), ('', 'FORWARD', reply)]:
|
||||
rules = [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', reply)]
|
||||
sources = row.get('allowed_sources', [])
|
||||
if sources:
|
||||
# Match the original public tuple even for connections created
|
||||
# before an edit changed the destination client.
|
||||
deny_match = f"-i {row['device']} -o {iface} -p {proto} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}"
|
||||
rules.append(('', 'FORWARD', f"{deny_match} -m comment --comment {tag}-deny -j DROP"))
|
||||
for index, source in enumerate(sources or ['']):
|
||||
source_match = f" -s {source}" if source else ''
|
||||
rules.append(('', 'FORWARD', f"{forward_match}{source_match} -m comment --comment {tag}-in{index} -j ACCEPT"))
|
||||
for table, chain, rule in rules:
|
||||
up.append(f"iptables -w{table} -I {chain} 1 {rule}")
|
||||
down.append(f"iptables -w{table} -D {chain} {rule} 2>/dev/null || true")
|
||||
if up:
|
||||
@@ -4521,7 +4539,7 @@ def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str
|
||||
return raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"})
|
||||
|
||||
|
||||
def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def extended_forward_add(iface: str, payload: dict[str, Any], *, update_id: str = '') -> dict[str, Any]:
|
||||
require_valid_iface(iface)
|
||||
try:
|
||||
public_ip = str(ipaddress.IPv4Address(payload.get("public_ip")))
|
||||
@@ -4530,6 +4548,15 @@ def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ValueError("Nieprawidłowy adres lub port") from exc
|
||||
protocol = str(payload.get("protocol") or "")
|
||||
sources = payload.get('allowed_sources') or []
|
||||
if not isinstance(sources, list) or len(sources) > 32:
|
||||
raise ValueError("Można podać maksymalnie 32 adresy źródłowe")
|
||||
try:
|
||||
sources = sorted({str(ipaddress.IPv4Address(value)) for value in sources})
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ValueError("Podaj poprawne adresy źródłowe IPv4") from exc
|
||||
if bool(payload.get('restrict_sources')) != bool(sources):
|
||||
raise ValueError("Podaj co najmniej jeden adres IPv4 albo wyłącz ograniczenie")
|
||||
if protocol not in {"tcp", "udp", "both"} or not (1 <= public_port <= 65535 and 1 <= target_port <= 65535):
|
||||
raise ValueError("Nieprawidłowy protokół lub port")
|
||||
if public_ip not in _extended_allowed(_extended_groups(), iface):
|
||||
@@ -4549,14 +4576,18 @@ def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if "udp" in protocols and (other_cfg.get("interface") or {}).get("listen_port") == public_port:
|
||||
raise ValueError("Ten port UDP jest używany przez WireGuard")
|
||||
for row in _extended_forwards(other):
|
||||
if other == iface and row['id'] == update_id:
|
||||
continue
|
||||
existing = {"tcp", "udp"} if row["protocol"] == "both" else {row["protocol"]}
|
||||
if row["public_ip"] == public_ip and row["public_port"] == public_port and protocols & existing:
|
||||
raise ValueError("Ten adres, port i protokół są już używane przez inne przekierowanie")
|
||||
rows = _extended_forwards(iface)
|
||||
if len(rows) >= 20:
|
||||
if update_id and not any(row['id'] == update_id for row in rows):
|
||||
raise ValueError("Nie znaleziono przekierowania")
|
||||
if not update_id and len(rows) >= 20:
|
||||
raise ValueError("Osiągnięto limit przekierowań w tej sieci")
|
||||
row = {"id": secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device}
|
||||
result = _extended_write_forwards(iface, [*rows, row])
|
||||
row = {"id": update_id or secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device, "allowed_sources": sources}
|
||||
result = _extended_write_forwards(iface, [*(item for item in rows if item['id'] != update_id), row])
|
||||
return {**result, "forward": row}
|
||||
|
||||
|
||||
@@ -6734,6 +6765,12 @@ def main() -> int:
|
||||
elif action == "extended_forward_add":
|
||||
payload = read_json_stdin()
|
||||
result = locked_call(lambda: extended_forward_add(iface, payload))
|
||||
elif action == "extended_forward_update":
|
||||
payload = read_json_stdin()
|
||||
identifier = str(payload.get('id') or '')
|
||||
if not re.fullmatch(r'[0-9a-f]{16}', identifier):
|
||||
raise ValueError("Nieprawidłowy identyfikator przekierowania")
|
||||
result = locked_call(lambda: extended_forward_add(iface, payload, update_id=identifier))
|
||||
elif action == "extended_forward_delete":
|
||||
payload = read_json_stdin()
|
||||
result = locked_call(lambda: extended_forward_delete(iface, payload))
|
||||
|
||||
Reference in new issue
Block a user