"""Private auxiliary contract, disabled until the board's auth adapter is accepted. No public Node/NodeDeployment registration, shared subscription UUID, office/GPS lookup, route advertisement, or production credential is created here. """ import hashlib import json import re import secrets from datetime import timedelta from django.conf import settings from django.http import JsonResponse from django.utils import timezone from django.utils.crypto import salted_hmac from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from .models import ClientSession, Subscription from .services import client_routing_rules SLUG = "jinan-private-aux" NAME = "优创未来·济南办(Zero3)" ADDRESS = "192.168.50.111" SCOPE = "private_auxiliary" def registered_address(): address = getattr(settings, "VPN_PRIVATE_AUXILIARY_ADDRESS", ADDRESS) return address if address in (ADDRESS, "192.168.50.170") else None def registered_name(): return "济南(博翠明湖)" if registered_address() == "192.168.50.170" else NAME def connect_address(): """Keep the phone's Ethernet registration distinct from its tailnet front door.""" registered = registered_address() endpoint = getattr(settings, "VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS", "") if not isinstance(endpoint, str): return None endpoint = endpoint or registered if endpoint == registered: return registered if registered == "192.168.50.170" and endpoint == "100.64.0.4": return endpoint if registered == "192.168.50.170" and endpoint == "vpn.toplc.cn": return endpoint return None def connection_endpoints(): address = connect_address() if registered_address() == "192.168.50.170": endpoints = [{"address": "100.64.0.4", "probe_ipv4": "100.64.0.4", "port": 18081}, {"address": "vpn.toplc.cn", "probe_ipv4": "192.0.2.1", "port": 11080}] if address == "192.168.50.170": endpoints.insert(0, {"address": address, "probe_ipv4": address, "port": 18081}) return endpoints return [{"address": ADDRESS, "probe_ipv4": ADDRESS, "port": 18081}] def site_config(for_verification=False): """Only a deliberately registered leaf/key pair can advertise the endpoint.""" if not getattr(settings, "VPN_PRIVATE_AUXILIARY_ENABLED", False) and not ( for_verification and getattr(settings, "VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID", 0) > 0 ): return None if registered_address() is None or connect_address() is None: return None pin = getattr(settings, "VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256", "") agent_hash = getattr(settings, "VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256", "") if not isinstance(pin, str) or not re.fullmatch(r"[a-fA-F0-9]{64}", pin): return None if not isinstance(agent_hash, str) or not re.fullmatch(r"[a-fA-F0-9]{64}", agent_hash): return None return pin.lower(), agent_hash.lower() def permitted(subscription): # Private metering and dedicated/custom policy admission are NOT yet wired. # Never let this auxiliary bypass a paid quota or a restricted subscription. return (subscription.is_usable and subscription.user.identity_type == "employee" and subscription.route_mode == Subscription.RouteMode.GLOBAL and subscription.traffic_limit_bytes == 0) def profile_grants(subscription): site = site_config() if not site or not permitted(subscription): return [] primary = next(e for e in connection_endpoints() if e["address"] == connect_address()) return [{"slug": SLUG, "name": registered_name(), "region": "济南", "status": "candidate", "probe_ipv4": primary["probe_ipv4"], "probe_port": primary["port"], "connect_address": primary["address"], "connection_endpoints": connection_endpoints(), "tls_leaf_sha256": site[0], "contract": 1, "expires_at": (timezone.now() + timedelta(minutes=15)).isoformat()}] def device_credential(session): # This is NOT the management bearer. Binding includes the login-session # digest and device; logout/key rotation invalidates the derived credential. payload = f"{SLUG}|{session.pk}|{session.device_id}|{session.token_digest}" mac = salted_hmac("ucvl.private-auxiliary.v1", payload, algorithm="sha256").hexdigest() return f"{session.pk}.{mac}" def credential_username(session): return f"ucvl-device-{session.device_id}" def reply(payload, status=200): response = JsonResponse(payload, status=status) response["Cache-Control"] = "no-store" return response @require_http_methods(["GET"]) def client_config(request): from .views import _authenticate_client_session session, error = _authenticate_client_session(request) if error: return error site = site_config() route = request.GET.get("route", "smart") if not site or not permitted(session.subscription) or request.GET.get("node") != SLUG: # 404 means private-only unavailable -> automatic public fallback; # reserve 401/403 above for invalid global account/device/session. return reply({"error": "私有辅助节点暂未开放。"}, 404) if route not in ("smart", "global"): return reply({"error": "私有辅助节点仅支持智能或全局 TCP 代理。"}, 400) selected_address = request.GET.get("endpoint", connect_address()) selected = next((e for e in connection_endpoints() if e["address"] == selected_address), None) if selected is None: return reply({"error": "所选连接入口未登记。"}, 400) expiry = min(timezone.now() + timedelta(minutes=10), session.expires_at) if session.subscription.expires_at: expiry = min(expiry, session.subscription.expires_at) sniff = {"enabled": True, "destOverride": ["http", "tls"], "routeOnly": True} config = { "log": {"loglevel": "warning"}, "inbounds": [ {"tag": "socks-in", "listen": "127.0.0.1", "port": 10808, "protocol": "socks", "settings": {"auth": "noauth", "udp": False}, "sniffing": sniff}, {"tag": "http-in", "listen": "127.0.0.1", "port": 10809, "protocol": "http", "settings": {}, "sniffing": sniff}], "outbounds": [ {"tag": "proxy", "protocol": "socks", "settings": {"servers": [ {"address": selected["address"], "port": selected["port"], "users": [ {"user": credential_username(session), "pass": device_credential(session)}]}]}, "streamSettings": {"network": "tcp", "security": "tls", "tlsSettings": { "serverName": "zero3-test", "minVersion": "1.2", "pinnedPeerCertSha256": site[0]}}}, {"tag": "direct", "protocol": "freedom"}, {"tag": "block", "protocol": "blackhole"}], "routing": {"domainStrategy": "IPIfNonMatch", "rules": client_routing_rules(route)}} return reply({"connection_scope": SCOPE, "config_contract": 3, "config_expires_at": expiry.isoformat(), "node": {"slug": SLUG, "name": registered_name(), "region": "济南"}, "route_mode": route, "config": config}) @csrf_exempt @require_http_methods(["POST"]) def verify_device(request): """Board checks CONNECT and every <=30s. Optional single-device acceptance does not advertise the node or supply proxy credentials to ordinary clients. """ site = site_config(for_verification=True) header = request.headers.get("Authorization", "") agent = header[7:] if header.startswith("Bearer ") else "" if not site or not 32 <= len(agent) <= 256 or not secrets.compare_digest( hashlib.sha256(agent.encode()).hexdigest(), site[1]): return reply({"allow": False}, 401) if len(request.body) > 2048: return reply({"allow": False}, 400) try: body = json.loads(request.body) if not isinstance(body, dict) or body.get("node") != SLUG or body.get("tls_leaf_sha256") != site[0]: raise ValueError token = body["credential"] if not isinstance(token, str) or not re.fullmatch(r"[1-9][0-9]{0,18}\.[a-f0-9]{64}", token): raise ValueError session = ClientSession.objects.select_related("device", "subscription__user", "subscription__plan").get( pk=int(token.partition(".")[0])) valid = (session.is_valid and session.device.active and session.device.subscription_id == session.subscription_id and permitted(session.subscription) and body.get("username") == credential_username(session) and secrets.compare_digest(token, device_credential(session))) if not getattr(settings, "VPN_PRIVATE_AUXILIARY_ENABLED", False): valid = valid and session.device_id == getattr(settings, "VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID", 0) if not valid: return reply({"allow": False}, 403) ttl = min(30, int((session.expires_at - timezone.now()).total_seconds())) if session.subscription.expires_at: ttl = min(ttl, int((session.subscription.expires_at - timezone.now()).total_seconds())) if ttl <= 0: return reply({"allow": False}, 403) return reply({"allow": True, "lease_seconds": ttl}) except (KeyError, TypeError, ValueError, ClientSession.DoesNotExist): return reply({"allow": False}, 403)