Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui_server): derive setup-host trust subnet from interface netmask

cyhbac7878114cf
diff --git a/pyproject.toml b/pyproject.toml
index ad1796e40..778b416ff 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -62,6 +62,7 @@ dependencies = [
"PyJWT[crypto]>=2.9.0",
"SQLAlchemy>=2.0.0",
"alembic>=1.13.0",
+ "psutil>=5.9.0",
]
[project.urls]
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index 69c7964d4..242cda878 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -1,5 +1,9 @@
from __future__ import annotations
+import ipaddress
+import socket
+from collections import namedtuple
+
from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
from config.v2_config import CONFIG_LOCK
from tests.ui_server_test_helpers import csrf_headers
@@ -9,6 +13,30 @@ from vibe import ui_server
from vibe.ui_server import app
+_FakeSnicaddr = namedtuple("snicaddr", ["family", "address", "netmask", "broadcast", "ptp"])
+
+
+def _mock_interface(monkeypatch, ip: str, prefix: int) -> None:
+ """Make ``psutil.net_if_addrs()`` report ``ip`` with the given prefix
+ length so ``_local_interface_network`` returns the expected subnet.
+ Tests that exercise the RFC1918/ULA trust path need this because the
+ real test runner does not have the synthetic addresses (192.168.2.3
+ etc.) configured on any interface."""
+ address = ipaddress.ip_address(ip)
+ if address.version == 4:
+ family = socket.AF_INET
+ netmask = str(ipaddress.IPv4Network(f"0.0.0.0/{prefix}").netmask)
+ else:
+ family = socket.AF_INET6
+ netmask = str(ipaddress.IPv6Network(f"::/{prefix}").netmask)
+ snic = _FakeSnicaddr(family=family, address=ip, netmask=netmask, broadcast=None, ptp=None)
+ monkeypatch.setattr("vibe.ui_server.psutil.net_if_addrs", lambda: {"en0": [snic]})
+
+
+def _mock_no_interfaces(monkeypatch) -> None:
+ monkeypatch.setattr("vibe.ui_server.psutil.net_if_addrs", lambda: {})
+
+
def _save_config(tmp_path) -> V2Config:
config = V2Config(
mode="self_host",
@@ -697,6 +725,7 @@ def _save_config_with_setup_host(tmp_path, host: str) -> V2Config:
def test_setup_host_lan_request_is_treated_as_local(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config_with_setup_host(tmp_path, "192.168.2.3")
+ _mock_interface(monkeypatch, "192.168.2.3", 24)
response = app.test_client().get(
"/health",
@@ -710,6 +739,7 @@ def test_setup_host_lan_request_is_treated_as_local(monkeypatch, tmp_path):
def test_setup_host_request_from_self_is_treated_as_local(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config_with_setup_host(tmp_path, "192.168.2.3")
+ _mock_interface(monkeypatch, "192.168.2.3", 24)
response = app.test_client().get(
"/health",
@@ -785,14 +815,15 @@ def test_setup_host_tailscale_peer_with_tailscale_setup_is_local(monkeypatch, tm
assert response.status_code == 200
-def test_setup_host_rfc1918_peer_in_different_24_is_not_local(monkeypatch, tmp_path):
+def test_setup_host_rfc1918_peer_outside_interface_subnet_is_not_local(monkeypatch, tmp_path):
"""RFC1918 trust must not span the entire /8: a 10.50/16 peer cannot
- inherit setup-host trust from a 10.1.2/24 setup_host even though both
- are in 10.0.0.0/8. Pre-wildcard, the kernel only let in peers on the
- same interface subnet — restoring that scoping at the application
- layer means /24 around setup_host, not the whole /8."""
+ inherit setup-host trust from a 10.1.2.3 setup_host configured with a
+ /24 mask. Pre-wildcard, the kernel only let in peers on the same
+ interface subnet — _local_interface_network restores that scoping
+ using the actual netmask."""
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config_with_setup_host(tmp_path, "10.1.2.3")
+ _mock_interface(monkeypatch, "10.1.2.3", 24)
response = app.test_client().get(
"/dashboard",
@@ -805,10 +836,11 @@ def test_setup_host_rfc1918_peer_in_different_24_is_not_local(monkeypatch, tmp_p
assert response.get_json()["error"] == "remote_access_host_mismatch"
-def test_setup_host_rfc1918_peer_in_same_24_is_local(monkeypatch, tmp_path):
- """Same-/24 RFC1918 peer still inherits trust (typical home/office LAN)."""
+def test_setup_host_rfc1918_peer_in_same_interface_subnet_is_local(monkeypatch, tmp_path):
+ """Same-subnet RFC1918 peer still inherits trust (typical home/office LAN)."""
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config_with_setup_host(tmp_path, "10.1.2.3")
+ _mock_interface(monkeypatch, "10.1.2.3", 24)
response = app.test_client().get(
"/health",
@@ -819,11 +851,12 @@ def test_setup_host_rfc1918_peer_in_same_24_is_local(monkeypatch, tmp_path):
assert response.status_code == 200
-def test_setup_host_192168_peer_in_different_24_is_not_local(monkeypatch, tmp_path):
- """A peer on 192.168.2/24 cannot spoof Host=192.168.1.5 even though both
- are in 192.168/16."""
+def test_setup_host_192168_peer_outside_interface_subnet_is_not_local(monkeypatch, tmp_path):
+ """A peer on 192.168.2/24 cannot spoof Host=192.168.1.5 when the
+ interface mask is /24."""
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config_with_setup_host(tmp_path, "192.168.1.5")
+ _mock_interface(monkeypatch, "192.168.1.5", 24)
response = app.test_client().get(
"/dashboard",
@@ -836,6 +869,109 @@ def test_setup_host_192168_peer_in_different_24_is_not_local(monkeypatch, tmp_pa
assert response.get_json()["error"] == "remote_access_host_mismatch"
+def test_setup_host_with_16_prefix_includes_peer_in_same_16(monkeypatch, tmp_path):
+ """When the interface mask is /16, a peer on a different /24 within
+ the same /16 still inherits trust — fixed-/24 estimates were too
+ narrow for /16 LANs."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "192.168.1.5")
+ _mock_interface(monkeypatch, "192.168.1.5", 16)
+
+ response = app.test_client().get(
+ "/health",
+ base_url="http://192.168.1.5:5123",
+ environ_base={"REMOTE_ADDR": "192.168.7.20"},
+ )
+
+ assert response.status_code == 200
+
+
+def test_setup_host_with_20_prefix_includes_peer_in_same_20(monkeypatch, tmp_path):
+ """/20 corporate networks (4096 addresses) are honored without
+ artificially narrowing to /24."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "10.1.16.5")
+ _mock_interface(monkeypatch, "10.1.16.5", 20)
+
+ response = app.test_client().get(
+ "/health",
+ base_url="http://10.1.16.5:5123",
+ environ_base={"REMOTE_ADDR": "10.1.31.250"},
+ )
+
+ assert response.status_code == 200
+
+
+def test_setup_host_with_20_prefix_excludes_peer_outside_20(monkeypatch, tmp_path):
+ """/20 still excludes peers outside the /20 (peer in next /20 is not
+ on the same routed subnet)."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "10.1.16.5")
+ _mock_interface(monkeypatch, "10.1.16.5", 20)
+
+ response = app.test_client().get(
+ "/dashboard",
+ base_url="http://10.1.16.5:5123",
+ environ_base={"REMOTE_ADDR": "10.1.32.5"},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 503
+ assert response.get_json()["error"] == "remote_access_host_mismatch"
+
+
+def test_setup_host_unknown_to_local_interfaces_is_not_local(monkeypatch, tmp_path):
+ """If setup_host is not configured on any local interface, deny trust
+ rather than guess a subnet — this preserves the kernel's pre-wildcard
+ "no matching interface, no traffic" semantics."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "192.168.99.99")
+ _mock_no_interfaces(monkeypatch)
+
+ response = app.test_client().get(
+ "/dashboard",
+ base_url="http://192.168.99.99:5123",
+ environ_base={"REMOTE_ADDR": "192.168.99.50"},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 503
+ assert response.get_json()["error"] == "remote_access_host_mismatch"
+
+
+def test_setup_host_ipv6_with_56_prefix_includes_peer_in_same_56(monkeypatch, tmp_path):
+ """A non-/64 IPv6 LAN (e.g. /56 prefix delegated to the home network)
+ is honored without artificially narrowing to /64."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "fd00:0:0:1::5")
+ _mock_interface(monkeypatch, "fd00:0:0:1::5", 56)
+
+ response = app.test_client().get(
+ "/health",
+ base_url="http://[fd00:0:0:1::5]:5123",
+ environ_base={"REMOTE_ADDR": "fd00:0:0:7::20"},
+ )
+
+ assert response.status_code == 200
+
+
+def test_setup_host_ipv6_with_64_prefix_excludes_peer_outside_64(monkeypatch, tmp_path):
+ """Default IPv6 LAN /64 still scopes peers correctly."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "fd00::5")
+ _mock_interface(monkeypatch, "fd00::5", 64)
+
+ response = app.test_client().get(
+ "/dashboard",
+ base_url="http://[fd00::5]:5123",
+ environ_base={"REMOTE_ADDR": "fd00:0:0:1::20"},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 503
+ assert response.get_json()["error"] == "remote_access_host_mismatch"
+
+
def test_setup_host_mismatched_host_header_is_not_local(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config_with_setup_host(tmp_path, "192.168.2.3")
diff --git a/uv.lock b/uv.lock
index c2396cadf..2637aa4fa 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1313,6 +1313,34 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5b/5a/bc7b4a4ef808fa59a816c17b20c4bef6884daebbdf627ff2a161da67da19/propcache-0.4.1-py3-none-any.whl", hash = "sha256:af2a6052aeb6cf17d3e46ee169099044fd8224cbaf75c76a2ef596e8163e2237", size = 13305, upload-time = "2025-10-08T19:49:00.792Z" },
]
+[[package]]
+name = "psutil"
+version = "7.2.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" },
+ { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" },
+ { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" },
+ { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" },
+ { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" },
+ { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" },
+ { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" },
+ { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" },
+]
+
[[package]]
name = "pycparser"
version = "2.23"
@@ -2050,6 +2078,7 @@ dependencies = [
{ name = "httpx", extra = ["socks"] },
{ name = "lark-oapi" },
{ name = "markdown-to-mrkdwn" },
+ { name = "psutil" },
{ name = "pyjwt", extra = ["crypto"] },
{ name = "python-socks", extra = ["asyncio"] },
{ name = "pyyaml" },
@@ -2074,6 +2103,7 @@ requires-dist = [
{ name = "httpx", extras = ["socks"], specifier = ">=0.27" },
{ name = "lark-oapi", specifier = ">=1.4.0" },
{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },
+ { name = "psutil", specifier = ">=5.9.0" },
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },
{ name = "python-socks", extras = ["asyncio"], specifier = ">=2.0.0" },
{ name = "pyyaml", specifier = ">=6.0" },
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 9911db3c9..d20da3ac0 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9,12 +9,14 @@ import mimetypes
import os
import re
import secrets
+import socket
import threading
from datetime import datetime
from pathlib import Path
from typing import Any
from urllib.parse import quote, unquote, urlparse, urlsplit, urlunsplit
+import psutil
from flask import Flask, request, jsonify, redirect, send_file, Response
from config import paths
@@ -271,15 +273,6 @@ _OVERLAY_TRUST_NETWORKS_V4 = (
ipaddress.IPv4Network("169.254.0.0/16"),
)
_OVERLAY_TRUST_NETWORKS_V6 = (ipaddress.IPv6Network("fe80::/10"),)
-# Subnet sizes used to approximate the kernel's pre-wildcard interface
-# filtering for RFC1918 / ULA setup hosts. The wildcard bind in the
-# tunnel-on path means we no longer get free interface scoping from the
-# kernel; we have to enforce "peer is on the same subnet as setup_host"
-# at the application layer. /24 and /64 cover typical home/office LANs
-# without granting trust across the whole /8 (10.0.0.0/8) or /7 (fc00::/7)
-# block, which would let a 10.50/16 peer spoof ``Host=10.20.x.y``.
-_DEFAULT_TRUST_PREFIX_V4 = 24
-_DEFAULT_TRUST_PREFIX_V6 = 64
def _is_private_address(address: ipaddress._BaseAddress) -> bool:
@@ -304,27 +297,96 @@ def _is_private_peer() -> bool:
return False
+def _local_interface_network(setup_address: ipaddress._BaseAddress) -> ipaddress._BaseNetwork | None:
+ """Return the network ``setup_host`` is configured on locally.
+
+ Reads the interface's actual netmask via ``psutil.net_if_addrs`` so
+ the trust scope mirrors the kernel's pre-wildcard interface filtering
+ exactly — a /16 LAN, a /20 corporate network, and a non-/64 IPv6
+ network all get their real prefix instead of a fixed estimate.
+
+ Returns None when ``setup_host`` is not configured on any local
+ interface or psutil cannot enumerate them; the caller denies trust
+ in that case so we never widen the application-layer scope beyond
+ what the kernel would have permitted.
+ """
+ try:
+ interfaces = psutil.net_if_addrs()
+ except Exception:
+ return None
+ target_family = socket.AF_INET if setup_address.version == 4 else socket.AF_INET6
+ for addrs in interfaces.values():
+ for snic in addrs:
+ if snic.family != target_family:
+ continue
+ address_str = (snic.address or "").split("%", 1)[0]
+ try:
+ addr = ipaddress.ip_address(address_str)
+ except ValueError:
+ continue
+ if addr != setup_address:
+ continue
+ netmask = snic.netmask
+ if not netmask:
+ continue
+ prefix = _netmask_to_prefix(netmask, addr.version)
+ if prefix is None:
+ continue
+ try:
+ return ipaddress.ip_network(f"{addr}/{prefix}", strict=False)
+ except ValueError:
+ continue
+ return None
+
+
+def _netmask_to_prefix(netmask: str, version: int) -> int | None:
+ """Convert ``psutil``'s netmask string to a prefix length.
+
+ psutil returns IPv4 netmasks as dotted strings (``255.255.255.0``)
+ and IPv6 netmasks as hex strings (``ffff:ffff:ffff:ff00::``).
+ ``ipaddress.ip_network`` only accepts the dotted form for IPv4 and
+ requires an integer prefix for IPv6, so we normalize to a prefix
+ length here. Returns None for malformed or non-contiguous masks.
+ """
+ try:
+ if version == 4:
+ mask_int = int(ipaddress.IPv4Address(netmask))
+ width = 32
+ else:
+ mask_int = int(ipaddress.IPv6Address(netmask))
+ width = 128
+ except (ipaddress.AddressValueError, ValueError):
+ return None
+ if mask_int == 0:
+ return 0
+ inverted = (~mask_int) & ((1 << width) - 1)
+ if inverted & (inverted + 1):
+ # Non-contiguous mask — refuse rather than guess.
+ return None
+ prefix = width - inverted.bit_length()
+ return prefix
+
+
def _setup_host_trust_network(setup_address: ipaddress._BaseAddress) -> ipaddress._BaseNetwork | None:
- """Return the network setup-host trust should extend to.
-
- Tailscale CGNAT and link-local ranges keep their natural block size
- because the overlay or kernel link-local routing scopes them. RFC1918
- and ULA setup hosts get a typical same-subnet prefix (/24 v4, /64 v6)
- around setup_host so we don't extend trust across an entire 10.0.0.0/8
- or fc00::/7 block — a 10.50/16 peer should not inherit trust from a
- 10.20/16 setup host.
+ """Return the network setup-host trust should extend to, or None to deny.
+
+ Overlay networks (Tailscale CGNAT, link-local) trust the entire block
+ because the overlay routing or kernel link-local scoping handles peer
+ isolation; legitimate peers can be anywhere in the block. RFC1918 and
+ ULA setup hosts derive the network from the actual interface netmask
+ via :func:`_local_interface_network` so the application-layer scope
+ matches the kernel's pre-wildcard interface filtering. Returning None
+ means the scope cannot be determined and the caller must deny trust.
"""
if setup_address.version == 4:
for overlay in _OVERLAY_TRUST_NETWORKS_V4:
if setup_address in overlay:
return overlay
- return ipaddress.ip_network(f"{setup_address}/{_DEFAULT_TRUST_PREFIX_V4}", strict=False)
- if setup_address.version == 6:
+ elif setup_address.version == 6:
for overlay in _OVERLAY_TRUST_NETWORKS_V6:
if setup_address in overlay:
return overlay
- return ipaddress.ip_network(f"{setup_address}/{_DEFAULT_TRUST_PREFIX_V6}", strict=False)
- return None
+ return _local_interface_network(setup_address)
def _peer_shares_setup_host_network(setup_address: ipaddress._BaseAddress) -> bool:
@@ -334,8 +396,8 @@ def _peer_shares_setup_host_network(setup_address: ipaddress._BaseAddress) -> bo
a 192.168/16 LAN peer could spoof ``Host=<tailscale_setup_host>`` on
a different interface and inherit setup-host trust. Subnet size comes
from :func:`_setup_host_trust_network`, which keeps overlay networks
- (Tailscale, link-local) broad and tightens RFC1918/ULA to /24 or /64
- around setup_host.
+ (Tailscale, link-local) broad and otherwise mirrors the actual
+ interface netmask via :func:`_local_interface_network`.
"""
remote_addr = (request.remote_addr or "").strip()
if not remote_addr or remote_addr == "localhost":