Skip to content

The agent that grows with you

fix: POSIX control-socket clients authenticate the listener's uid

Teknium8b5688d6e069
diff --git a/gateway/control_socket.py b/gateway/control_socket.py
index 52899caca00..2d60877d987 100644
--- a/gateway/control_socket.py
+++ b/gateway/control_socket.py
@@ -18,7 +18,6 @@ import logging
import os
import socket
import stat
-import struct
import sys
import tempfile
import time
@@ -284,26 +283,13 @@ class GatewayControlServer:
if os.name == "nt":
return None
try:
- from hermes_cli.gateway_runtime_discovery import home_mode_unsafe
+ from hermes_cli.gateway_runtime_discovery import home_mode_unsafe, socket_peer_uid
home = self._home
info = home.lstat()
if (home.absolute() != home.resolve() or not stat.S_ISDIR(info.st_mode)
or info.st_uid != os.getuid() or home_mode_unsafe(info, home)): # windows-footgun: ok — POSIX-only helper
return None
- sock = writer.get_extra_info("socket")
- if hasattr(socket, "SO_PEERCRED"):
- _, uid, _ = struct.unpack("3i", sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
- elif sys.platform == "darwin":
- import ctypes
- uid_value, gid_value = ctypes.c_uint(), ctypes.c_uint()
- getpeereid = ctypes.CDLL(None, use_errno=True).getpeereid
- getpeereid.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)]
- getpeereid.restype = ctypes.c_int
- if getpeereid(sock.fileno(), ctypes.byref(uid_value), ctypes.byref(gid_value)) != 0:
- return None
- uid = uid_value.value
- else:
- return None
+ uid = socket_peer_uid(writer.get_extra_info("socket"))
return f"uid:{uid}" if uid == os.getuid() else None # windows-footgun: ok — POSIX-only helper
except OSError:
return None
diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.py
index 657fc47f441..496c4d11f5a 100644
--- a/gateway/session_hosted_transport.py
+++ b/gateway/session_hosted_transport.py
@@ -12,7 +12,6 @@ import hashlib
import json
import os
from pathlib import Path
-import socket
import threading
import time
@@ -60,11 +59,9 @@ def owner_request(home, verb, params, *, timeout=30):
from gateway.runtime_bootstrap_windows import query_runtime_control
raw = query_runtime_control(home, request, timeout)
else:
- from hermes_cli.gateway_runtime_discovery import _socket_path
+ from hermes_cli.gateway_runtime_discovery import connect_private
from gateway.control_socket import _read_response_line
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
- peer.settimeout(timeout)
- peer.connect(str(_socket_path(home)))
+ with connect_private(home, timeout) as peer:
peer.sendall(request)
def read():
peer.settimeout(max(0.001, deadline - time.monotonic()))
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index e561a05f302..f45c51cc86f 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -6,7 +6,6 @@ from contextlib import asynccontextmanager, suppress
import json
import os
from pathlib import Path
-import socket
import time
@@ -73,7 +72,7 @@ class GatewayClient:
def _session_ticket(home: Path, endpoint, *, purpose="interactive") -> str:
from hermes_cli.gateway_runtime import control_home_for
- from hermes_cli.gateway_runtime_discovery import _socket_path, _identify_response
+ from hermes_cli.gateway_runtime_discovery import connect_private, _identify_response
# A served secondary's ticket is minted by the multiplexer's socket, bound to the secondary.
home = control_home_for(home, endpoint)
request = json.dumps({"protocol": 1, "id": 1, "verb": "session-ticket", "params": {
@@ -84,9 +83,7 @@ def _session_ticket(home: Path, endpoint, *, purpose="interactive") -> str:
data = query_runtime_control(home, request, 5)
else:
deadline = time.monotonic() + 5
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
- peer.settimeout(5)
- peer.connect(str(_socket_path(home)))
+ with connect_private(home, 5) as peer:
peer.sendall(request)
data = bytearray()
while b"\n" not in data:
diff --git a/hermes_cli/gateway_runtime_discovery.py b/hermes_cli/gateway_runtime_discovery.py
index 33d57ebe0d0..a04bc35165b 100644
--- a/hermes_cli/gateway_runtime_discovery.py
+++ b/hermes_cli/gateway_runtime_discovery.py
@@ -8,6 +8,7 @@ import os
from pathlib import Path
import socket
import stat
+import sys
from typing import Literal
import time
@@ -68,6 +69,43 @@ def _private_node(path: Path, *, kind: str, home: bool = False) -> os.stat_resul
return node
+def socket_peer_uid(sock: socket.socket) -> int | None:
+ """Kernel-reported uid of the process on the other end of a connected AF_UNIX socket
+ (SO_PEERCRED on Linux, getpeereid on macOS); None where neither exists."""
+ if hasattr(socket, "SO_PEERCRED"):
+ import struct
+ return struct.unpack("3i", sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))[1]
+ if sys.platform != "darwin":
+ return None
+ import ctypes
+ uid, gid = ctypes.c_uint(), ctypes.c_uint()
+ getpeereid = ctypes.CDLL(None, use_errno=True).getpeereid
+ getpeereid.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)]
+ getpeereid.restype = ctypes.c_int
+ if getpeereid(sock.fileno(), ctypes.byref(uid), ctypes.byref(gid)) != 0:
+ raise OSError(ctypes.get_errno(), "getpeereid failed")
+ return uid.value
+
+
+def connect_private(home: Path, timeout: float) -> socket.socket:
+ """Connected control socket for *home* whose listener runs as this user (caller closes it).
+ The path is validated by lstat first, but connect() follows a symlink swapped in afterwards,
+ so the listening process itself is authenticated. Platforms without a peer-credential API
+ (neither SO_PEERCRED nor getpeereid) fall back to the path checks alone."""
+ path = _socket_path(home)
+ peer = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ peer.settimeout(timeout)
+ peer.connect(str(path))
+ uid = socket_peer_uid(peer)
+ if uid is not None and uid != os.getuid(): # windows-footgun: ok — POSIX socket peer only
+ raise DiscoveryError("unsafe_control_peer")
+ return peer
+ except BaseException:
+ peer.close()
+ raise
+
+
def _socket_path(home: Path) -> Path:
_private_node(home, kind="directory", home=True)
direct = home / "gateway.sock"
@@ -108,14 +146,8 @@ def query_identify(home: Path, *, timeout: float) -> dict:
return _identify_response(query_runtime_control(
home, b'{"protocol":1,"verb":"identify","id":1}\n', timeout))
deadline = time.monotonic() + timeout
- path = _socket_path(home)
request = b'{"protocol":1,"verb":"identify","id":1}\n'
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
- budget = deadline - time.monotonic()
- if budget <= 0:
- raise TimeoutError
- client.settimeout(budget)
- client.connect(str(path))
+ with connect_private(home, timeout) as client:
budget = deadline - time.monotonic()
if budget <= 0:
raise TimeoutError
diff --git a/tests/gateway/test_control_socket_peer_security.py b/tests/gateway/test_control_socket_peer_security.py
index 070e8429bc5..5a0739afbcd 100644
--- a/tests/gateway/test_control_socket_peer_security.py
+++ b/tests/gateway/test_control_socket_peer_security.py
@@ -62,3 +62,37 @@ def test_group_bits_that_are_an_acl_mask_never_count_as_a_private_group(tmp_path
def get_extra_info(self, _key):
return ours
assert GatewayControlServer(home)._posix_peer_subject(Writer()) is None
+
+
+def test_clients_refuse_a_control_listener_run_by_another_uid(tmp_path, monkeypatch):
+ # lstat validates the path, but connect() follows a symlink swapped in afterwards: the
+ # client must authenticate the listening process itself (SO_PEERCRED / getpeereid).
+ import asyncio
+ import inspect
+ from gateway import control_socket, session_hosted_transport
+ from hermes_cli import gateway_client
+ from hermes_cli import gateway_runtime_discovery as discovery
+ home = tmp_path / "home"
+ home.mkdir(mode=0o700)
+ real_uid = os.getuid()
+
+ async def run():
+ server = control_socket.GatewayControlServer(home, verb_handlers={"identify": lambda: {"pid": 1}})
+ assert await server.start()
+ try:
+ path = discovery._socket_path(home)
+ monkeypatch.setattr(discovery.os, "getuid", lambda: real_uid + 1)
+ monkeypatch.setattr(discovery, "_socket_path", lambda _home: path)
+ with pytest.raises(discovery.DiscoveryError, match="unsafe_control_peer"):
+ await asyncio.to_thread(discovery.query_identify, home, timeout=2)
+ finally:
+ monkeypatch.undo()
+ await server.stop()
+ asyncio.run(run())
+ import importlib.util
+ spec = importlib.util.spec_from_file_location("tui_bootstrap", "ui-tui/scripts/gateway_bootstrap.py")
+ tui_bootstrap = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(tui_bootstrap)
+ for client in (gateway_client._session_ticket, session_hosted_transport.owner_request, tui_bootstrap.bootstrap):
+ source = inspect.getsource(client)
+ assert "connect_private(" in source and "AF_UNIX" not in source, client.__qualname__
diff --git a/tests/tui_gateway/test_gateway_bootstrap_control_home.py b/tests/tui_gateway/test_gateway_bootstrap_control_home.py
index 3c36826eae6..171d193b819 100644
--- a/tests/tui_gateway/test_gateway_bootstrap_control_home.py
+++ b/tests/tui_gateway/test_gateway_bootstrap_control_home.py
@@ -86,24 +86,17 @@ def test_served_secondary_uses_multiplexer_control_home(monkeypatch, tmp_path):
def __exit__(self, *args):
return False
- def settimeout(self, timeout):
- seen["timeout"] = timeout
-
- def connect(self, target):
- seen["socket"] = target
-
def sendall(self, request):
seen["request"] = json.loads(request)
def makefile(self, _mode):
return FakeStream()
- def socket_path(home):
+ def connect_private(home, timeout):
seen["control_home"] = Path(home).resolve()
- return Path("/fake/gateway.sock")
+ return FakeSocket()
- monkeypatch.setattr(discovery, "_socket_path", socket_path)
- monkeypatch.setattr(module.socket, "socket", lambda *_a, **_k: FakeSocket())
+ monkeypatch.setattr(discovery, "connect_private", connect_private)
result = module.bootstrap(False)
diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.py
index a54fe1c6bb7..71d274789be 100644
--- a/ui-tui/scripts/gateway_bootstrap.py
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -3,7 +3,6 @@ import contextlib
import json
import os
from pathlib import Path
-import socket
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
@@ -12,7 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
def bootstrap(start: bool) -> dict:
from hermes_constants import get_hermes_home
from hermes_cli.gateway_runtime import control_home_for, discover_gateway_endpoint, ensure_gateway_runtime
- from hermes_cli.gateway_runtime_discovery import _socket_path
+ from hermes_cli.gateway_runtime_discovery import connect_private
home = get_hermes_home().resolve()
# Launch policy travels in session.create, not into daemon-wide defaults.
@@ -34,9 +33,7 @@ def bootstrap(start: bool) -> dict:
from gateway.runtime_bootstrap_windows import query_runtime_control
raw = query_runtime_control(control, request, 5)
else:
- with socket.socket(socket.AF_UNIX) as peer:
- peer.settimeout(5)
- peer.connect(str(_socket_path(control)))
+ with connect_private(control, 5) as peer:
peer.sendall(request)
with peer.makefile("rb") as stream:
raw = stream.readline(65537)