Files
ucvl-zonghengjia-open-source/backend/control/tailscale_endpoint.py
T

68 lines
2.6 KiB
Python
Raw Normal View History

"""Optional same-node transport hint; never an authorization or dispatch policy."""
import ipaddress
import json
import re
from django.conf import settings
from .models import Node
_TAILSCALE_IPV4 = ipaddress.ip_network("100.64.0.0/10")
def _unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate endpoint setting")
result[key] = value
return result
def _configured_endpoints():
# Parse only administrator-supplied settings, never request parameters.
raw = getattr(settings, "VPN_TAILSCALE_ENDPOINTS_JSON", "")
if not isinstance(raw, str) or not raw or len(raw) > 16384:
return {}
try:
entries = json.loads(raw, object_pairs_hook=_unique_object)
if not isinstance(entries, dict) or len(entries) > 64:
return {}
for slug, endpoint in entries.items():
if not re.fullmatch(r"[a-zA-Z0-9_-]{1,100}", slug):
return {}
if not isinstance(endpoint, dict) or set(endpoint) != {"address", "port"}:
return {}
address, port = endpoint["address"], endpoint["port"]
if not isinstance(address, str):
return {}
parsed = ipaddress.IPv4Address(address)
if (str(parsed) != address or parsed not in _TAILSCALE_IPV4
or parsed in (_TAILSCALE_IPV4.network_address, _TAILSCALE_IPV4.broadcast_address)
or address == "100.100.100.100"):
return {}
if type(port) is not int or not 1 <= port <= 65535:
return {}
return entries
except (ValueError, TypeError, RecursionError):
# Invalid optional configuration must not break the existing public entry.
return {}
def client_tailscale_endpoint(session, node):
"""Called after config authentication/rendering; recheck the grant defensively."""
if getattr(settings, "VPN_TAILSCALE_ENDPOINT_ENABLED", False) is not True:
return None
subscription = session.subscription
if (not session.is_valid or not session.device.active
or session.device.subscription_id != session.subscription_id
or subscription.user.identity_type != "employee" or not subscription.is_usable):
return None
endpoint = _configured_endpoints().get(node.slug)
if endpoint is None or not subscription.nodes_for_subscription().filter(
pk=node.pk, protocol=Node.Protocol.VLESS_REALITY).exists():
return None
return {"contract": 1, "node_slug": node.slug,
"address": endpoint["address"], "port": endpoint["port"]}