public inbox for git-commits@fedoraproject.org
help / color / mirror / Atom feed
From: Michel Lind <salimma@fedoraproject.org>
To: git-commits@fedoraproject.org
Subject: [rpms/et] f43: Backport security fixes from 7.1.x and disable telemetry
Date: Wed, 11 Nov 2026 21:10:38 GMT [thread overview]
Message-ID: <179443143818.1.15225279562933160192.rpms-et-9ebc65f49583@fedoraproject.org> (raw)
A new commit has been pushed.
Repo : rpms/et
Branch : f43
Commit : 9ebc65f4958327384286f35758adf5e2d05c3fff
Author : Michel Lind <salimma@fedoraproject.org>
Date : 2026-11-11T16:48:14+00:00
Stats : +3824/-26 in 2 file(s)
URL : https://src.fedoraproject.org/rpms/et/c/9ebc65f4958327384286f35758adf5e2d05c3fff?branch=f43
Log:
Backport security fixes from 7.1.x and disable telemetry
- Backport upstream fixes for pre-authentication denial of service,
daemon aborts on malformed input, and root file operations and
connections on client-chosen Unix socket paths
- Build with DISABLE_TELEMETRY on all architectures, which drops the
bundled sentry-native, its fixed paths in /tmp (CVE-2023-23558) and
the libcurl dependency; default et.cfg to telemetry = false
- Correct the bundled() Provides and License: versions from the
submodules pinned at the tag, unused bundled copies removed in prep
Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Michel Lind <salimma@fedoraproject.org>
---
diff --git a/et-6.2.11-security-backports.patch b/et-6.2.11-security-backports.patch
new file mode 100644
index 0000000..58de2f2
--- /dev/null
+++ b/et-6.2.11-security-backports.patch
@@ -0,0 +1,3775 @@
+From 0c51f8818a8e927d767635ce4cfbd0d9505cf39b Mon Sep 17 00:00:00 2001
+From: Jason Gauci <jgmath2000@gmail.com>
+Date: Wed, 11 Nov 2026 11:10:09 +0000
+Subject: [PATCH 01/12] Fix four pre-auth and privilege-escalation issues from
+ security notices. (#784)
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+* Fix four pre-auth and privilege-escalation issues from security notices.
+
+Address ANT-2026-5PETM5BV, ANT-2026-VAMER5RC, ANT-2026-AVTT7HQH, and
+ANT-2026-A3WQS3AG without bumping PROTOCOL_VERSION.
+
+ANT-2026-5PETM5BV (pre-auth DoS): The fixed 8-thread client handler pool
+read ConnectRequest via readProto, which trusted a client length up to
+128 MiB and allocated up front. readAll() also reset its 30s idle timer
+on every byte, so a slow trickle could hold a worker forever. Cap
+handshake protos at 4 KiB, and enforce both idle and absolute (60s)
+deadlines in readAll—checking the absolute deadline every loop iteration
+so a steady trickle cannot bypass it.
+
+ANT-2026-VAMER5RC (pre-auth reconnect crash / disconnect): Returning
+clients were accepted on cleartext clientId alone. recoverClient() closed
+the live victim socket before reading a plaintext SequenceHeader, and
+BackedWriter::recover() used STFATAL/LOG(FATAL) when the attacker-supplied
+sequence was ahead of the server—aborting the root daemon. Treat a bad
+sequence as a caught runtime_error, and only close the old socket after
+recover succeeds so a failed reconnect leaves the session intact.
+
+ANT-2026-AVTT7HQH / ANT-2026-A3WQS3AG (unix-socket LPE as root): etserver
+never drops privileges, so reverse-tunnel sources ran root unlink/bind/
+chmod/chown on client-chosen paths (arbitrary file delete + chown TOCTOU),
+and forward destinations connected as root to arbitrary AF_UNIX paths
+(e.g. docker.sock). Add UserSocketOps: fork, setgroups/setgid/setuid to
+the session user, perform listen/connect, and return the fd via SCM_RIGHTS.
+PortForwardHandler uses this for unix source listen and destination
+connect; path-based chown after bind is removed.
+
+Unsolved without a PROTOCOL_VERSION bump: reconnect still does not prove
+passkey knowledge before recover. ConnectRequest carries only clientId and
+version; adding challenge-response (or encrypting the recover handshake)
+would break old clients that must match PROTOCOL_VERSION exactly. Residual
+risk: an on-path observer who sniffs a live clientId and supplies an
+acceptable sequence number can still displace that session's TCP
+connection and force-disconnect the victim. They cannot speak the
+encrypted session without the passkey, and they can no longer crash the
+daemon with a crafted sequence. Full reconnect authentication remains a
+coordinated future protocol change.
+
+Add SecurityNoticesTest and UserSocketOps coverage for each fixed case.
+
+Co-authored-by: Cursor <cursoragent@cursor.com>
+
+* Fix security notice tests when CI runs as root.
+
+Debian/FreeBSD portability jobs run et-test as root, so DAC-based checks
+(chmod 0555 directories, mode-000 sockets) were bypassed when the session uid
+was also 0. Target an unprivileged user (nobody) for privilege-drop
+tests so setuid actually loses the ability to unlink/connect, matching
+the etserver-as-root threat model.
+
+Co-authored-by: Cursor <cursoragent@cursor.com>
+
+* Harden absolute-timeout security test against CI hangs.
+
+Make the trickle socket non-blocking and always close/join the writer via
+RAII so a failed assertion cannot leave a stuck thread. Also reject macOS's
+nobody sentinel uid when selecting a privilege-drop test user.
+
+Co-authored-by: Cursor <cursoragent@cursor.com>
+
+* Raise patch coverage for UserSocketOps and privilege-dropped sockets.
+
+Expose in-process listen/connect helpers, flush gcov before forked _exit,
+and add tests for error paths, PipeSocketHandler as-user APIs, and
+recoverClient success.
+
+Co-authored-by: Cursor <cursoragent@cursor.com>
+
+---------
+
+Co-authored-by: Jason Gauci <jason.gauci@webai.com>
+Co-authored-by: Cursor <cursoragent@cursor.com>
+(cherry picked from commit 69b33537ab12f324cf619aca04dc483728dc30c3)
+
+Backport to 6.2.11: conflicts only in comments and context; dropped the
+additions to BackedIOTest, ClientConnectionTest and UnixSocketHandlerTest,
+which do not exist in 6.2.11; new tests moved from test/unit_tests/ to test/.
+
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ CMakeLists.txt | 7 +-
+ src/base/BackedWriter.cpp | 4 +-
+ src/base/Connection.cpp | 3 +-
+ src/base/PipeSocketHandler.cpp | 43 ++
+ src/base/PipeSocketHandler.hpp | 18 +
+ src/base/ServerClientConnection.cpp | 33 +-
+ src/base/ServerClientConnection.hpp | 4 +
+ src/base/ServerConnection.cpp | 4 +-
+ src/base/SocketHandler.cpp | 31 +-
+ src/base/SocketHandler.hpp | 52 +-
+ src/base/UserSocketOps.cpp | 269 +++++++++
+ src/base/UserSocketOps.hpp | 56 ++
+ src/terminal/TerminalServer.cpp | 4 +-
+ .../forwarding/ForwardSourceHandler.cpp | 6 +-
+ .../forwarding/ForwardSourceHandler.hpp | 8 +-
+ .../forwarding/PortForwardHandler.cpp | 43 +-
+ .../forwarding/PortForwardHandler.hpp | 17 +-
+ test/SecurityNoticesTest.cpp | 561 ++++++++++++++++++
+ test/UserSocketOpsTest.cpp | 173 ++++++
+ 19 files changed, 1305 insertions(+), 31 deletions(-)
+ create mode 100644 src/base/UserSocketOps.cpp
+ create mode 100644 src/base/UserSocketOps.hpp
+ create mode 100644 test/SecurityNoticesTest.cpp
+ create mode 100644 test/UserSocketOpsTest.cpp
+
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 7d57438e1..0a1a83ff3 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -189,8 +189,9 @@ IF(WIN32)
+ ENDIF(WIN32)
+
+ if(CODE_COVERAGE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
+- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g --coverage")
+- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g --coverage")
++ # CODE_COVERAGE define lets forked children flush gcov before _exit.
++ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g --coverage -DCODE_COVERAGE")
++ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g --coverage -DCODE_COVERAGE")
+ endif(CODE_COVERAGE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
+
+ if(DISABLE_CRASH_LOG)
+@@ -369,6 +370,8 @@ add_library(
+ src/base/SocketHandler.cpp
+ src/base/PipeSocketHandler.hpp
+ src/base/PipeSocketHandler.cpp
++ src/base/UserSocketOps.hpp
++ src/base/UserSocketOps.cpp
+ src/base/TcpSocketHandler.hpp
+ src/base/TcpSocketHandler.cpp
+ src/base/UnixSocketHandler.hpp
+diff --git a/src/base/BackedWriter.cpp b/src/base/BackedWriter.cpp
+index 56a94b68a..8ed9f199f 100644
+--- a/src/base/BackedWriter.cpp
++++ b/src/base/BackedWriter.cpp
+@@ -80,7 +80,9 @@ vector<std::string> BackedWriter::recover(int64_t lastValidSequenceNumber) {
+
+ int64_t messagesToRecover = sequenceNumber - lastValidSequenceNumber;
+ if (messagesToRecover < 0) {
+- STFATAL << "Something went really wrong, client is ahead of server";
++ // Attacker-controlled sequence numbers must not abort the process.
++ throw std::runtime_error(
++ "Invalid recovery sequence: client is ahead of server");
+ }
+ if (messagesToRecover == 0) {
+ return vector<std::string>();
+diff --git a/src/base/Connection.cpp b/src/base/Connection.cpp
+index 90d569d74..2c7859c07 100644
+--- a/src/base/Connection.cpp
++++ b/src/base/Connection.cpp
+@@ -109,7 +109,8 @@ bool Connection::recover(int newSocketFd) {
+
+ // Read the remote sequence number
+ et::SequenceHeader remoteHeader =
+- socketHandler->readProto<et::SequenceHeader>(newSocketFd, true);
++ socketHandler->readProto<et::SequenceHeader>(
++ newSocketFd, true, SocketHandler::MAX_HANDSHAKE_PROTO_LENGTH);
+
+ {
+ // Fetch the catchup bytes and send
+diff --git a/src/base/PipeSocketHandler.cpp b/src/base/PipeSocketHandler.cpp
+index 509a05d65..d856bd59e 100644
+--- a/src/base/PipeSocketHandler.cpp
++++ b/src/base/PipeSocketHandler.cpp
+@@ -1,5 +1,9 @@
+ #include "PipeSocketHandler.hpp"
+
++#ifndef WIN32
++#include "UserSocketOps.hpp"
++#endif
++
+ namespace et {
+ PipeSocketHandler::PipeSocketHandler() {}
+
+@@ -90,6 +94,24 @@ int PipeSocketHandler::connect(const SocketEndpoint& endpoint) {
+ return sockFd;
+ }
+
++#ifndef WIN32
++int PipeSocketHandler::connectAsUser(const SocketEndpoint& endpoint, uid_t uid,
++ gid_t gid) {
++ lock_guard<std::recursive_mutex> mutexGuard(globalMutex);
++
++ string pipePath = endpoint.name();
++ VLOG(3) << "Connecting to " << endpoint << " as uid " << uid;
++ int sockFd = UserSocketOps::connectUnixAsUser(pipePath, uid, gid);
++ if (sockFd < 0) {
++ return -1;
++ }
++ initSocket(sockFd);
++ addToActiveSockets(sockFd);
++ LOG(INFO) << "Connected to endpoint " << endpoint << " as uid " << uid;
++ return sockFd;
++}
++#endif
++
+ set<int> PipeSocketHandler::listen(const SocketEndpoint& endpoint) {
+ lock_guard<std::recursive_mutex> guard(globalMutex);
+
+@@ -117,6 +139,27 @@ set<int> PipeSocketHandler::listen(const SocketEndpoint& endpoint) {
+ return pipeServerSockets[pipePath];
+ }
+
++#ifndef WIN32
++set<int> PipeSocketHandler::listenAsUser(const SocketEndpoint& endpoint,
++ uid_t uid, gid_t gid) {
++ lock_guard<std::recursive_mutex> guard(globalMutex);
++
++ string pipePath = endpoint.name();
++ if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {
++ throw runtime_error("Tried to listen twice on the same path");
++ }
++
++ int fd = UserSocketOps::listenUnixAsUser(pipePath, uid, gid);
++ if (fd < 0) {
++ throw runtime_error(string("Failed to listen as user on ") + pipePath +
++ ": " + strerror(GetErrno()));
++ }
++ initServerSocket(fd);
++ pipeServerSockets[pipePath] = set<int>({fd});
++ return pipeServerSockets[pipePath];
++}
++#endif
++
+ set<int> PipeSocketHandler::getEndpointFds(const SocketEndpoint& endpoint) {
+ lock_guard<std::recursive_mutex> guard(globalMutex);
+
+diff --git a/src/base/PipeSocketHandler.hpp b/src/base/PipeSocketHandler.hpp
+index 697120e3a..3250f2c31 100644
+--- a/src/base/PipeSocketHandler.hpp
++++ b/src/base/PipeSocketHandler.hpp
+@@ -10,7 +10,25 @@ class PipeSocketHandler : public UnixSocketHandler {
+ virtual ~PipeSocketHandler() {}
+
+ virtual int connect(const SocketEndpoint& endpoint);
++#ifndef WIN32
++ /**
++ * @brief Connects to a UNIX socket after dropping to @p uid/@p gid.
++ */
++ int connectAsUser(const SocketEndpoint& endpoint, uid_t uid, gid_t gid);
++#endif
++ /**
++ * @brief Creates a listening UNIX socket and stores it internally.
++ */
+ virtual set<int> listen(const SocketEndpoint& endpoint);
++#ifndef WIN32
++ /**
++ * @brief Creates a listening UNIX socket after dropping to @p uid/@p gid.
++ */
++ set<int> listenAsUser(const SocketEndpoint& endpoint, uid_t uid, gid_t gid);
++#endif
++ /**
++ * @brief Returns the listening fds for a previously registered pipe.
++ */
+ virtual set<int> getEndpointFds(const SocketEndpoint& endpoint);
+ virtual void stopListening(const SocketEndpoint& endpoint);
+
+diff --git a/src/base/ServerClientConnection.cpp b/src/base/ServerClientConnection.cpp
+index 32883eabc..3005f6491 100644
+--- a/src/base/ServerClientConnection.cpp
++++ b/src/base/ServerClientConnection.cpp
+@@ -25,13 +25,40 @@ ServerClientConnection::~ServerClientConnection() {
+ }
+
+ bool ServerClientConnection::recoverClient(int newSocketFd) {
++ // Detach the live session without closing it until recover succeeds, so a
++ // failed/malicious reconnect cannot force-disconnect the victim.
++ int oldSocketFd = -1;
+ {
+ lock_guard<std::recursive_mutex> guard(connectionMutex);
+- if (socketFd != -1) {
+- closeSocket();
++ oldSocketFd = socketFd;
++ if (reader) {
++ reader->invalidateSocket();
++ }
++ if (writer) {
++ writer->invalidateSocket();
++ }
++ socketFd = -1;
++ }
++
++ bool success = recover(newSocketFd);
++ if (success) {
++ if (oldSocketFd != -1) {
++ socketHandler->close(oldSocketFd);
++ }
++ return true;
++ }
++
++ if (oldSocketFd != -1) {
++ lock_guard<std::recursive_mutex> guard(connectionMutex);
++ socketFd = oldSocketFd;
++ if (reader) {
++ reader->revive(oldSocketFd, vector<string>());
++ }
++ if (writer) {
++ writer->revive(oldSocketFd);
+ }
+ }
+- return recover(newSocketFd);
++ return false;
+ }
+
+ bool ServerClientConnection::verifyPasskey(const string& targetKey) {
+diff --git a/src/base/ServerClientConnection.hpp b/src/base/ServerClientConnection.hpp
+index 5bdc687e9..721dd8388 100644
+--- a/src/base/ServerClientConnection.hpp
++++ b/src/base/ServerClientConnection.hpp
+@@ -13,6 +13,10 @@ class ServerClientConnection : public Connection {
+
+ virtual ~ServerClientConnection();
+
++ /**
++ * @brief Attempts recovery on the new fd; closes the old socket only after
++ * recover succeeds.
++ */
+ bool recoverClient(int newSocketFd);
+
+ bool verifyPasskey(const string& targetKey);
+diff --git a/src/base/ServerConnection.cpp b/src/base/ServerConnection.cpp
+index 95aeee4a2..e91d4bb13 100644
+--- a/src/base/ServerConnection.cpp
++++ b/src/base/ServerConnection.cpp
+@@ -41,8 +41,8 @@ void ServerConnection::clientHandler(int clientSocketFd) {
+ string clientId;
+ bool createdClientConnection = false;
+ try {
+- et::ConnectRequest request =
+- socketHandler->readProto<et::ConnectRequest>(clientSocketFd, true);
++ et::ConnectRequest request = socketHandler->readProto<et::ConnectRequest>(
++ clientSocketFd, true, SocketHandler::MAX_HANDSHAKE_PROTO_LENGTH);
+ {
+ int version = request.version();
+ if (version != PROTOCOL_VERSION) {
+diff --git a/src/base/SocketHandler.cpp b/src/base/SocketHandler.cpp
+index 90fb0a4ba..efcb5e133 100644
+--- a/src/base/SocketHandler.cpp
++++ b/src/base/SocketHandler.cpp
+@@ -3,17 +3,33 @@
+ #include "base64.h"
+
+ namespace et {
+-#define SOCKET_DATA_TRANSFER_TIMEOUT (30)
++#define SOCKET_DATA_TRANSFER_TIMEOUT (SocketHandler::SOCKET_IDLE_TIMEOUT_SEC)
+
+ void SocketHandler::readAll(int fd, void* buf, size_t count, bool timeout) {
+- time_t startTime = time(NULL);
++ if (timeout) {
++ readAll(fd, buf, count, SOCKET_IDLE_TIMEOUT_SEC,
++ SOCKET_ABSOLUTE_TIMEOUT_SEC);
++ } else {
++ readAll(fd, buf, count, 0, 0);
++ }
++}
++
++void SocketHandler::readAll(int fd, void* buf, size_t count, int idleTimeoutSec,
++ int absoluteTimeoutSec) {
++ time_t absoluteStartTime = time(NULL);
++ time_t idleStartTime = absoluteStartTime;
+ size_t pos = 0;
+ while (pos < count) {
++ // Enforce deadlines on every iteration so a slow trickle that keeps the
++ // idle timer reset cannot hold the read open past the absolute limit.
++ time_t currentTime = time(NULL);
++ if ((idleTimeoutSec > 0 && currentTime > idleStartTime + idleTimeoutSec) ||
++ (absoluteTimeoutSec > 0 &&
++ currentTime > absoluteStartTime + absoluteTimeoutSec)) {
++ throw std::runtime_error("Socket Timeout");
++ }
++
+ if (!waitOnSocketData(fd)) {
+- time_t currentTime = time(NULL);
+- if (timeout && currentTime > startTime + SOCKET_DATA_TRANSFER_TIMEOUT) {
+- throw std::runtime_error("Socket Timeout");
+- }
+ continue;
+ }
+
+@@ -36,7 +52,8 @@ void SocketHandler::readAll(int fd, void* buf, size_t count, bool timeout) {
+ }
+ } else {
+ pos += bytesRead;
+- startTime = time(NULL);
++ // Only the idle timer resets on progress; absolute deadline does not.
++ idleStartTime = time(NULL);
+ }
+ }
+ }
+diff --git a/src/base/SocketHandler.hpp b/src/base/SocketHandler.hpp
+index 1c861566b..fb1a5674c 100644
+--- a/src/base/SocketHandler.hpp
++++ b/src/base/SocketHandler.hpp
+@@ -13,19 +13,67 @@ class SocketHandler {
+ virtual ssize_t read(int fd, void* buf, size_t count) = 0;
+ virtual ssize_t write(int fd, const void* buf, size_t count) = 0;
+
++ /** @brief Idle-gap timeout (seconds) used when `readAll(..., true)`. */
++ static constexpr int SOCKET_IDLE_TIMEOUT_SEC = 30;
++ /**
++ * @brief Absolute read deadline (seconds) used when `readAll(..., true)`.
++ * Unlike the idle timeout, this is not reset when bytes arrive.
++ */
++ static constexpr int SOCKET_ABSOLUTE_TIMEOUT_SEC = 60;
++
++ /**
++ * @brief Reads exactly `count` bytes, retrying on EAGAIN until the buffer
++ * fills.
++ * @param timeout Whether to enforce idle + absolute transfer timeouts.
++ */
+ void readAll(int fd, void* buf, size_t count, bool timeout);
++ /**
++ * @brief Reads exactly `count` bytes with explicit deadlines.
++ * @param idleTimeoutSec Max seconds without any progress; 0 disables.
++ * @param absoluteTimeoutSec Max seconds for the whole read; 0 disables.
++ */
++ void readAll(int fd, void* buf, size_t count, int idleTimeoutSec,
++ int absoluteTimeoutSec);
++ /**
++ * @brief Attempts to write the full buffer and returns -1 on timeout/failure.
++ * @return Total bytes written or -1 when the socket deadlocks.
++ */
+ int writeAllOrReturn(int fd, const void* buf, size_t count);
+ void writeAllOrThrow(int fd, const void* buf, size_t count, bool timeout);
+
++ /** @brief Default max length for length-prefixed protobuf reads (128 MiB). */
++ static constexpr int64_t DEFAULT_MAX_PROTO_LENGTH = 128 * 1024 * 1024;
++ /**
++ * @brief Max length for pre-authentication / handshake protos (4 KiB).
++ *
++ * ConnectRequest and SequenceHeader are tiny; a large declared length would
++ * pin memory on a handler thread before any auth.
++ */
++ static constexpr int64_t MAX_HANDSHAKE_PROTO_LENGTH = 4 * 1024;
++
++ /**
++ * @brief Reads a length-prefixed protobuf from the socket.
++ * @tparam T Protobuf message type.
++ * @throws std::runtime_error on invalid length or parse failure.
++ */
+ template <typename T>
+ inline T readProto(int fd, bool timeout) {
++ return readProto<T>(fd, timeout, DEFAULT_MAX_PROTO_LENGTH);
++ }
++
++ /**
++ * @brief Reads a length-prefixed protobuf, rejecting lengths above @p
++ * maxLength.
++ */
++ template <typename T>
++ inline T readProto(int fd, bool timeout, int64_t maxLength) {
+ T t;
+ int64_t length;
+ readAll(fd, &length, sizeof(int64_t), timeout);
+- if (length < 0 || length > 128 * 1024 * 1024) {
++ if (length < 0 || length > maxLength) {
+ // If the message is <= 0 or too big, assume this is a bad packet and
+ // throw
+- string s = string("Invalid size (<0 or >128 MB): ") + to_string(length);
++ string s = string("Invalid size (<0 or >max): ") + to_string(length);
+ throw std::runtime_error(s.c_str());
+ }
+ if (length == 0) {
+diff --git a/src/base/UserSocketOps.cpp b/src/base/UserSocketOps.cpp
+new file mode 100644
+index 000000000..0cfbd6533
+--- /dev/null
++++ b/src/base/UserSocketOps.cpp
+@@ -0,0 +1,269 @@
++#include "UserSocketOps.hpp"
++
++#ifndef WIN32
++#include <sys/socket.h>
++#include <sys/un.h>
++#include <sys/wait.h>
++#include <unistd.h>
++
++#ifdef CODE_COVERAGE
++extern "C" void __gcov_dump(void);
++#endif
++
++namespace et {
++namespace {
++struct ResultHeader {
++ int status; // 0 ok, -1 error
++ int err;
++};
++
++void fatalClose(int fd) {
++ if (fd >= 0) {
++ ::close(fd);
++ }
++}
++
++bool pathTooLong(const string& path) {
++ return path.size() >= sizeof(sockaddr_un::sun_path);
++}
++} // namespace
++
++void UserSocketOps::coverageExit(int code) {
++#ifdef CODE_COVERAGE
++ // _exit skips atexit/gcov flush; dump so forked child lines count in reports.
++ __gcov_dump();
++#endif
++ _exit(code);
++}
++
++void UserSocketOps::sendFd(int channel, int fdToSend, int status, int err) {
++ ResultHeader header{status, err};
++ struct iovec iov;
++ iov.iov_base = &header;
++ iov.iov_len = sizeof(header);
++
++ char control[CMSG_SPACE(sizeof(int))];
++ memset(control, 0, sizeof(control));
++
++ struct msghdr msg;
++ memset(&msg, 0, sizeof(msg));
++ msg.msg_iov = &iov;
++ msg.msg_iovlen = 1;
++
++ if (status == 0 && fdToSend >= 0) {
++ msg.msg_control = control;
++ msg.msg_controllen = sizeof(control);
++ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
++ cmsg->cmsg_level = SOL_SOCKET;
++ cmsg->cmsg_type = SCM_RIGHTS;
++ cmsg->cmsg_len = CMSG_LEN(sizeof(int));
++ memcpy(CMSG_DATA(cmsg), &fdToSend, sizeof(int));
++ }
++
++ // Best-effort; child exits immediately after.
++ ::sendmsg(channel, &msg, 0);
++}
++
++int UserSocketOps::recvFd(int channel, int* errOut) {
++ ResultHeader header;
++ struct iovec iov;
++ iov.iov_base = &header;
++ iov.iov_len = sizeof(header);
++
++ char control[CMSG_SPACE(sizeof(int))];
++ memset(control, 0, sizeof(control));
++
++ struct msghdr msg;
++ memset(&msg, 0, sizeof(msg));
++ msg.msg_iov = &iov;
++ msg.msg_iovlen = 1;
++ msg.msg_control = control;
++ msg.msg_controllen = sizeof(control);
++
++ ssize_t n = ::recvmsg(channel, &msg, 0);
++ if (n != (ssize_t)sizeof(header)) {
++ if (errOut) {
++ *errOut = EIO;
++ }
++ return -1;
++ }
++ if (header.status != 0) {
++ if (errOut) {
++ *errOut = header.err ? header.err : EIO;
++ }
++ return -1;
++ }
++
++ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
++ if (cmsg == nullptr || cmsg->cmsg_level != SOL_SOCKET ||
++ cmsg->cmsg_type != SCM_RIGHTS || cmsg->cmsg_len < CMSG_LEN(sizeof(int))) {
++ if (errOut) {
++ *errOut = EIO;
++ }
++ return -1;
++ }
++ int fd = -1;
++ memcpy(&fd, CMSG_DATA(cmsg), sizeof(int));
++ if (errOut) {
++ *errOut = 0;
++ }
++ return fd;
++}
++
++int UserSocketOps::listenAtPath(const string& path) {
++ if (pathTooLong(path)) {
++ SetErrno(ENAMETOOLONG);
++ return -1;
++ }
++
++ int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
++ if (fd < 0) {
++ return -1;
++ }
++
++ sockaddr_un local;
++ memset(&local, 0, sizeof(local));
++ local.sun_family = AF_UNIX;
++ strncpy(local.sun_path, path.c_str(), sizeof(local.sun_path) - 1);
++
++ // Only removes a path the current credentials can unlink.
++ ::unlink(local.sun_path);
++
++ if (::bind(fd, (struct sockaddr*)&local, sizeof(local)) < 0) {
++ int err = errno;
++ fatalClose(fd);
++ SetErrno(err);
++ return -1;
++ }
++ if (::listen(fd, 5) < 0) {
++ int err = errno;
++ fatalClose(fd);
++ SetErrno(err);
++ return -1;
++ }
++ if (::fchmod(fd, S_IRUSR | S_IWUSR | S_IXUSR) < 0) {
++ // fchmod on unix sockets is unsupported on some platforms; fall back to
++ // path chmod. Still running with the caller's credentials.
++ ::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR);
++ }
++ return fd;
++}
++
++int UserSocketOps::connectAtPath(const string& path) {
++ if (pathTooLong(path)) {
++ SetErrno(ENAMETOOLONG);
++ return -1;
++ }
++
++ int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
++ if (fd < 0) {
++ return -1;
++ }
++
++ sockaddr_un remote;
++ memset(&remote, 0, sizeof(remote));
++ remote.sun_family = AF_UNIX;
++ strncpy(remote.sun_path, path.c_str(), sizeof(remote.sun_path) - 1);
++
++ if (::connect(fd, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
++ int err = errno;
++ fatalClose(fd);
++ SetErrno(err);
++ return -1;
++ }
++ return fd;
++}
++
++void UserSocketOps::childListen(int resultFd, const string& path) {
++ int fd = listenAtPath(path);
++ if (fd < 0) {
++ sendFd(resultFd, -1, -1, GetErrno());
++ coverageExit(1);
++ }
++ sendFd(resultFd, fd, 0, 0);
++ fatalClose(fd);
++ coverageExit(0);
++}
++
++void UserSocketOps::childConnect(int resultFd, const string& path) {
++ int fd = connectAtPath(path);
++ if (fd < 0) {
++ sendFd(resultFd, -1, -1, GetErrno());
++ coverageExit(1);
++ }
++ sendFd(resultFd, fd, 0, 0);
++ fatalClose(fd);
++ coverageExit(0);
++}
++
++int UserSocketOps::runAsUser(Op op, const string& path, uid_t uid, gid_t gid) {
++ int sv[2];
++ if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
++ return -1;
++ }
++
++ pid_t pid = ::fork();
++ if (pid < 0) {
++ int err = errno;
++ fatalClose(sv[0]);
++ fatalClose(sv[1]);
++ SetErrno(err);
++ return -1;
++ }
++
++ if (pid == 0) {
++ fatalClose(sv[0]);
++ // Drop privileges before any path operation. Do not use logging here.
++ // Clear supplemental groups when running as root so we do not retain the
++ // parent's group set. setgroups(2) requires privilege and is skipped
++ // otherwise (e.g. already-unprivileged test processes).
++ if (::geteuid() == 0) {
++ if (::setgroups(1, &gid) != 0) {
++ sendFd(sv[1], -1, -1, errno);
++ coverageExit(1);
++ }
++ }
++ if (::setgid(gid) != 0) {
++ sendFd(sv[1], -1, -1, errno);
++ coverageExit(1);
++ }
++ if (::setuid(uid) != 0) {
++ sendFd(sv[1], -1, -1, errno);
++ coverageExit(1);
++ }
++ if (op == Op::LISTEN) {
++ childListen(sv[1], path);
++ } else {
++ childConnect(sv[1], path);
++ }
++ coverageExit(1);
++ }
++
++ fatalClose(sv[1]);
++ int err = 0;
++ int fd = recvFd(sv[0], &err);
++ fatalClose(sv[0]);
++
++ int status = 0;
++ while (::waitpid(pid, &status, 0) < 0) {
++ if (errno != EINTR) {
++ break;
++ }
++ }
++
++ if (fd < 0) {
++ SetErrno(err ? err : EIO);
++ return -1;
++ }
++ return fd;
++}
++
++int UserSocketOps::listenUnixAsUser(const string& path, uid_t uid, gid_t gid) {
++ return runAsUser(Op::LISTEN, path, uid, gid);
++}
++
++int UserSocketOps::connectUnixAsUser(const string& path, uid_t uid, gid_t gid) {
++ return runAsUser(Op::CONNECT, path, uid, gid);
++}
++} // namespace et
++#endif
+diff --git a/src/base/UserSocketOps.hpp b/src/base/UserSocketOps.hpp
+new file mode 100644
+index 000000000..cc07040da
+--- /dev/null
++++ b/src/base/UserSocketOps.hpp
+@@ -0,0 +1,56 @@
++#ifndef __ET_USER_SOCKET_OPS__
++#define __ET_USER_SOCKET_OPS__
++
++#include "Headers.hpp"
++
++namespace et {
++#ifndef WIN32
++/**
++ * @brief Create or connect UNIX sockets after dropping to a session uid/gid.
++ *
++ * etserver is multithreaded and cannot safely seteuid in-process. These helpers
++ * fork a child, drop privileges, perform the socket operation, and return the
++ * resulting fd to the parent via SCM_RIGHTS.
++ */
++class UserSocketOps {
++ public:
++ /**
++ * @brief unlink/bind/listen/fchmod a UNIX socket path as @p uid/@p gid.
++ * @return Listening fd owned by the caller, or -1 on failure (errno set).
++ */
++ static int listenUnixAsUser(const string& path, uid_t uid, gid_t gid);
++
++ /**
++ * @brief connect() to a UNIX socket path as @p uid/@p gid.
++ * @return Connected fd owned by the caller, or -1 on failure (errno set).
++ */
++ static int connectUnixAsUser(const string& path, uid_t uid, gid_t gid);
++
++ /**
++ * @brief Create a listening UNIX socket at @p path in the current process.
++ *
++ * Used after privilege drop in the forked child, and directly by unit tests.
++ * @return Listening fd, or -1 with errno set.
++ */
++ static int listenAtPath(const string& path);
++
++ /**
++ * @brief Connect to a UNIX socket at @p path in the current process.
++ * @return Connected fd, or -1 with errno set.
++ */
++ static int connectAtPath(const string& path);
++
++ private:
++ enum class Op : int { LISTEN = 1, CONNECT = 2 };
++
++ static int runAsUser(Op op, const string& path, uid_t uid, gid_t gid);
++ static void childListen(int resultFd, const string& path);
++ static void childConnect(int resultFd, const string& path);
++ static void sendFd(int channel, int fdToSend, int status, int err);
++ static int recvFd(int channel, int* errOut);
++ static void coverageExit(int code);
++};
++#endif
++} // namespace et
++
++#endif // __ET_USER_SOCKET_OPS__
+diff --git a/src/terminal/TerminalServer.cpp b/src/terminal/TerminalServer.cpp
+index 6366cdd8c..cbf90f284 100644
+--- a/src/terminal/TerminalServer.cpp
++++ b/src/terminal/TerminalServer.cpp
+@@ -210,8 +210,8 @@ void TerminalServer::runTerminal(
+ InitialResponse response;
+ shared_ptr<SocketHandler> serverSocketHandler = getSocketHandler();
+ shared_ptr<SocketHandler> pipeSocketHandler(new PipeSocketHandler());
+- shared_ptr<PortForwardHandler> portForwardHandler(
+- new PortForwardHandler(serverSocketHandler, pipeSocketHandler));
++ shared_ptr<PortForwardHandler> portForwardHandler(new PortForwardHandler(
++ serverSocketHandler, pipeSocketHandler, userInfo.uid(), userInfo.gid()));
+ map<string, string> environmentVariables;
+ vector<string> pipePaths;
+ for (const PortForwardSourceRequest &pfsr : payload.reversetunnels()) {
+diff --git a/src/terminal/forwarding/ForwardSourceHandler.cpp b/src/terminal/forwarding/ForwardSourceHandler.cpp
+index 1d62af027..438aae78b 100644
+--- a/src/terminal/forwarding/ForwardSourceHandler.cpp
++++ b/src/terminal/forwarding/ForwardSourceHandler.cpp
+@@ -3,11 +3,13 @@
+ namespace et {
+ ForwardSourceHandler::ForwardSourceHandler(
+ shared_ptr<SocketHandler> _socketHandler, const SocketEndpoint& _source,
+- const SocketEndpoint& _destination)
++ const SocketEndpoint& _destination, bool alreadyListening)
+ : socketHandler(_socketHandler),
+ source(_source),
+ destination(_destination) {
+- socketHandler->listen(source);
++ if (!alreadyListening) {
++ socketHandler->listen(source);
++ }
+ }
+
+ ForwardSourceHandler::~ForwardSourceHandler() {
+diff --git a/src/terminal/forwarding/ForwardSourceHandler.hpp b/src/terminal/forwarding/ForwardSourceHandler.hpp
+index facfb644d..723ea13b4 100644
+--- a/src/terminal/forwarding/ForwardSourceHandler.hpp
++++ b/src/terminal/forwarding/ForwardSourceHandler.hpp
+@@ -7,9 +7,15 @@
+ namespace et {
+ class ForwardSourceHandler {
+ public:
++ /**
++ * @brief Creates source/destination handlers used for local port forwarding.
++ * @param alreadyListening If true, skip listen(); caller already registered
++ * the source endpoint (e.g. via listenAsUser).
++ */
+ ForwardSourceHandler(shared_ptr<SocketHandler> _socketHandler,
+ const SocketEndpoint& _source,
+- const SocketEndpoint& _destination);
++ const SocketEndpoint& _destination,
++ bool alreadyListening = false);
+
+ ~ForwardSourceHandler();
+
+diff --git a/src/terminal/forwarding/PortForwardHandler.cpp b/src/terminal/forwarding/PortForwardHandler.cpp
+index df70c01c1..a4480a3b0 100644
+--- a/src/terminal/forwarding/PortForwardHandler.cpp
++++ b/src/terminal/forwarding/PortForwardHandler.cpp
+@@ -1,11 +1,17 @@
+ #include "PortForwardHandler.hpp"
+
++#include <cstdint>
++
++#include "PipeSocketHandler.hpp"
++
+ namespace et {
+ PortForwardHandler::PortForwardHandler(
+ shared_ptr<SocketHandler> _networkSocketHandler,
+- shared_ptr<SocketHandler> _pipeSocketHandler)
++ shared_ptr<SocketHandler> _pipeSocketHandler, uid_t userid, gid_t groupid)
+ : networkSocketHandler(_networkSocketHandler),
+- pipeSocketHandler(_pipeSocketHandler) {}
++ pipeSocketHandler(_pipeSocketHandler),
++ sessionUid(userid),
++ sessionGid(groupid) {}
+
+ void PortForwardHandler::update(vector<PortForwardDestinationRequest>* requests,
+ vector<PortForwardData>* dataToSend) {
+@@ -72,14 +78,23 @@ PortForwardSourceResponse PortForwardHandler::createSource(
+ sourceHandlers.push_back(handler);
+ return PortForwardSourceResponse();
+ } else {
+- if (userid < 0 || groupid < 0) {
+- STFATAL
+- << "Tried to create a unix socket forward with no userid/groupid";
++#ifndef WIN32
++ // Perform unlink/bind/listen as the session user so a client-chosen path
++ // cannot delete or chown root-owned files.
++ auto concretePipe =
++ dynamic_pointer_cast<PipeSocketHandler>(pipeSocketHandler);
++ if (concretePipe && userid != static_cast<uid_t>(-1) &&
++ groupid != static_cast<gid_t>(-1)) {
++ concretePipe->listenAsUser(source, userid, groupid);
++ auto handler =
++ shared_ptr<ForwardSourceHandler>(new ForwardSourceHandler(
++ pipeSocketHandler, source, pfsr.destination(), true));
++ sourceHandlers.push_back(handler);
++ return PortForwardSourceResponse();
+ }
++#endif
+ auto handler = shared_ptr<ForwardSourceHandler>(new ForwardSourceHandler(
+ pipeSocketHandler, source, pfsr.destination()));
+- FATAL_FAIL(::chmod(source.name().c_str(), S_IRUSR | S_IWUSR | S_IXUSR));
+- FATAL_FAIL(::chown(source.name().c_str(), userid, groupid));
+ sourceHandlers.push_back(handler);
+ return PortForwardSourceResponse();
+ }
+@@ -110,7 +125,21 @@ PortForwardDestinationResponse PortForwardHandler::createDestination(
+ fd = networkSocketHandler->connect(ipv4Localhost);
+ }
+ } else {
++#ifndef WIN32
++ // Connect as the session user so root etserver cannot open privileged
++ // sockets (e.g. docker.sock) on behalf of an unprivileged client.
++ auto concretePipe =
++ dynamic_pointer_cast<PipeSocketHandler>(pipeSocketHandler);
++ if (concretePipe && sessionUid != static_cast<uid_t>(-1) &&
++ sessionGid != static_cast<gid_t>(-1)) {
++ fd = concretePipe->connectAsUser(pfdr.destination(), sessionUid,
++ sessionGid);
++ } else {
++ fd = pipeSocketHandler->connect(pfdr.destination());
++ }
++#else
+ fd = pipeSocketHandler->connect(pfdr.destination());
++#endif
+ }
+ PortForwardDestinationResponse pfdresponse;
+ pfdresponse.set_clientfd(pfdr.fd());
+diff --git a/src/terminal/forwarding/PortForwardHandler.hpp b/src/terminal/forwarding/PortForwardHandler.hpp
+index dfcaffb92..dd82ee768 100644
+--- a/src/terminal/forwarding/PortForwardHandler.hpp
++++ b/src/terminal/forwarding/PortForwardHandler.hpp
+@@ -10,8 +10,18 @@
+ namespace et {
+ class PortForwardHandler {
+ public:
++ /**
++ * @brief Constructs forwarding helpers for network and router sockets.
++ * @param userid Session uid used for privilege-dropped UNIX socket ops
++ * ((uid_t)-1 to disable).
++ * @param groupid Session gid used with @p userid.
++ */
+ explicit PortForwardHandler(shared_ptr<SocketHandler> _networkSocketHandler,
+- shared_ptr<SocketHandler> _pipeSocketHandler);
++ shared_ptr<SocketHandler> _pipeSocketHandler,
++ uid_t userid = static_cast<uid_t>(-1),
++ gid_t groupid = static_cast<gid_t>(-1));
++ /** @brief Polls all handlers for new destination/data and sends
++ * `PortForwardData`. */
+ void update(vector<PortForwardDestinationRequest>* requests,
+ vector<PortForwardData>* dataToSend);
+ void handlePacket(const Packet& packet, shared_ptr<Connection> connection);
+@@ -31,6 +41,11 @@ class PortForwardHandler {
+ protected:
+ shared_ptr<SocketHandler> networkSocketHandler;
+ shared_ptr<SocketHandler> pipeSocketHandler;
++ /** @brief Session uid for UNIX connect/listen; (uid_t)-1 disables drop. */
++ uid_t sessionUid;
++ /** @brief Session gid for UNIX connect/listen; (gid_t)-1 disables drop. */
++ gid_t sessionGid;
++ /** @brief Active destination handlers keyed by socket id. */
+ unordered_map<int, shared_ptr<ForwardDestinationHandler>> destinationHandlers;
+
+ vector<shared_ptr<ForwardSourceHandler>> sourceHandlers;
+diff --git a/test/SecurityNoticesTest.cpp b/test/SecurityNoticesTest.cpp
+new file mode 100644
+index 000000000..668cfb380
+--- /dev/null
++++ b/test/SecurityNoticesTest.cpp
+@@ -0,0 +1,561 @@
++/**
++ * Regression tests for public security notices under security_notices/.
++ *
++ * ANT-2026-VAMER5RC reconnect passkey proof is intentionally not covered: that
++ * requires a PROTOCOL_VERSION bump / wire-format change.
++ */
++
++#include <fcntl.h>
++#include <pwd.h>
++#include <sys/stat.h>
++#include <unistd.h>
++
++#include <atomic>
++#include <chrono>
++#include <deque>
++#include <map>
++#include <queue>
++#include <thread>
++
++#include "BackedWriter.hpp"
++#include "PipeSocketHandler.hpp"
++#include "PortForwardHandler.hpp"
++#include "ServerClientConnection.hpp"
++#include "ServerConnection.hpp"
++#include "TestHeaders.hpp"
++#include "UserSocketOps.hpp"
++
++using namespace et;
++
++namespace {
++// Minimal socket handler that works with socketpairs for handshake tests.
++class SocketPairHandler : public SocketHandler {
++ public:
++ void queueConnectFd(int fd) { connectQueue.push(fd); }
++
++ bool hasData(int fd) override { return waitOnSocketData(fd); }
++
++ ssize_t read(int fd, void* buf, size_t count) override {
++ return ::read(fd, buf, count);
++ }
++
++ ssize_t write(int fd, const void* buf, size_t count) override {
++ return ::write(fd, buf, count);
++ }
++
++ int connect(const SocketEndpoint&) override {
++ if (connectQueue.empty()) {
++ return -1;
++ }
++ int fd = connectQueue.front();
++ connectQueue.pop();
++ return fd;
++ }
++
++ set<int> listen(const SocketEndpoint&) override { return {}; }
++ set<int> getEndpointFds(const SocketEndpoint&) override { return {}; }
++ int accept(int fd) override { return fd; }
++ void stopListening(const SocketEndpoint&) override {}
++ void close(int fd) override { ::close(fd); }
++ vector<int> getActiveSockets() override { return {}; }
++
++ private:
++ std::queue<int> connectQueue;
++};
++
++class RecordingServerConnection : public ServerConnection {
++ public:
++ RecordingServerConnection(std::shared_ptr<SocketHandler> socketHandler,
++ const SocketEndpoint& endpoint)
++ : ServerConnection(std::move(socketHandler), endpoint) {}
++
++ bool newClient(
++ shared_ptr<ServerClientConnection> serverClientState) override {
++ return true;
++ }
++};
++
++class FdSocketHandler : public SocketHandler {
++ public:
++ bool hasData(int fd) override { return waitOnSocketData(fd); }
++ ssize_t read(int fd, void* buf, size_t count) override {
++ return ::read(fd, buf, count);
++ }
++ ssize_t write(int fd, const void* buf, size_t count) override {
++ return ::write(fd, buf, count);
++ }
++ int connect(const SocketEndpoint&) override { return -1; }
++ set<int> listen(const SocketEndpoint&) override { return {}; }
++ set<int> getEndpointFds(const SocketEndpoint&) override { return {}; }
++ int accept(int) override { return -1; }
++ void stopListening(const SocketEndpoint&) override {}
++ void close(int fd) override { ::close(fd); }
++ vector<int> getActiveSockets() override { return {}; }
++};
++
++string makeTempDir() {
++ string pattern = GetTempDirectory() + "et_secnotice_XXXXXX";
++ string dir = string(mkdtemp(&pattern[0]));
++ REQUIRE_FALSE(dir.empty());
++ return dir;
++}
++
++// CI containers (Debian/FreeBSD) run tests as root. Privilege-drop tests must
++// target a non-root uid so DAC actually applies after setuid.
++bool unprivilegedTestUser(uid_t* uid, gid_t* gid) {
++ if (getuid() != 0) {
++ *uid = getuid();
++ *gid = getgid();
++ return true;
++ }
++ const char* candidates[] = {"nobody", "nfsnobody", nullptr};
++ for (int i = 0; candidates[i] != nullptr; ++i) {
++ struct passwd* pw = getpwnam(candidates[i]);
++ // Reject uid 0 and macOS's nobody sentinel ((uid_t)-2 == 4294967294).
++ // Allow traditional nobody (65534) used on Linux/FreeBSD.
++ if (pw != nullptr && pw->pw_uid != 0 && pw->pw_uid <= 65534) {
++ *uid = pw->pw_uid;
++ *gid = pw->pw_gid;
++ return true;
++ }
++ }
++ return false;
++}
++} // namespace
++
++// ---------------------------------------------------------------------------
++// ANT-2026-5PETM5BV — pre-auth slowloris / oversized ConnectRequest
++// ---------------------------------------------------------------------------
++
++TEST_CASE(
++ "ANT-2026-5PETM5BV handshake readProto rejects oversized length before "
++ "allocating",
++ "[SecurityNotice][ANT-2026-5PETM5BV]") {
++ FdSocketHandler handler;
++ int fds[2];
++ REQUIRE(::pipe(fds) == 0);
++
++ // Exactly the old 128 MiB cap must also be rejected for handshake reads.
++ int64_t oversize = 128 * 1024 * 1024;
++ REQUIRE(oversize > SocketHandler::MAX_HANDSHAKE_PROTO_LENGTH);
++ REQUIRE(handler.writeAllOrReturn(fds[1], &oversize, sizeof(oversize)) ==
++ (int)sizeof(oversize));
++
++ REQUIRE_THROWS_AS(
++ handler.readProto<ConnectRequest>(
++ fds[0], true, SocketHandler::MAX_HANDSHAKE_PROTO_LENGTH),
++ std::runtime_error);
++
++ handler.close(fds[0]);
++ handler.close(fds[1]);
++}
++
++TEST_CASE(
++ "ANT-2026-5PETM5BV readAll absolute timeout fires under per-byte trickle",
++ "[SecurityNotice][ANT-2026-5PETM5BV]") {
++ FdSocketHandler handler;
++ int fds[2];
++ REQUIRE(::socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
++ // Non-blocking so a spuriously-readable fd cannot block forever inside
++ // read() and skip absolute-deadline checks.
++ for (int fd : {fds[0], fds[1]}) {
++ int flags = ::fcntl(fd, F_GETFL, 0);
++ REQUIRE(flags >= 0);
++ REQUIRE(::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0);
++ }
++
++ std::atomic<bool> stop{false};
++ std::thread trickle([&]() {
++ // Keep resetting the idle timer with 1 byte ~every 200ms; without an
++ // absolute deadline this would never time out.
++ char b = 'x';
++ while (!stop.load()) {
++ ssize_t n = ::write(fds[1], &b, 1);
++ if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
++ return;
++ }
++ std::this_thread::sleep_for(std::chrono::milliseconds(200));
++ }
++ });
++
++ // Always stop the writer and join, even on assertion failure.
++ struct TrickleGuard {
++ std::atomic<bool>& stop;
++ std::thread& trickle;
++ int& writeFd;
++ int& readFd;
++ ~TrickleGuard() {
++ stop.store(true);
++ if (writeFd >= 0) {
++ ::close(writeFd);
++ writeFd = -1;
++ }
++ if (trickle.joinable()) {
++ trickle.join();
++ }
++ if (readFd >= 0) {
++ ::close(readFd);
++ readFd = -1;
++ }
++ }
++ } guard{stop, trickle, fds[1], fds[0]};
++
++ char buf[256];
++ auto start = std::chrono::steady_clock::now();
++ // Idle allowance is long; absolute deadline is short.
++ REQUIRE_THROWS_AS(handler.readAll(fds[0], buf, sizeof(buf), /*idle*/ 30,
++ /*absolute*/ 2),
++ std::runtime_error);
++ auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(
++ std::chrono::steady_clock::now() - start)
++ .count();
++ // Must not wait anywhere near the 30s idle timeout.
++ REQUIRE(elapsedMs < 15000);
++}
++
++TEST_CASE(
++ "ANT-2026-5PETM5BV ServerConnection rejects oversized ConnectRequest "
++ "length",
++ "[SecurityNotice][ANT-2026-5PETM5BV][ServerConnection]") {
++ auto handler = make_shared<SocketPairHandler>();
++ SocketEndpoint endpoint;
++ endpoint.set_name("server");
++ RecordingServerConnection server(handler, endpoint);
++
++ int fds[2];
++ REQUIRE(::socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
++
++ int64_t oversize = SocketHandler::MAX_HANDSHAKE_PROTO_LENGTH + 1;
++ REQUIRE(handler->writeAllOrReturn(fds[0], &oversize, sizeof(oversize)) ==
++ (int)sizeof(oversize));
++
++ // Must return (catch runtime_error), not abort the process.
++ REQUIRE_NOTHROW(server.clientHandler(fds[1]));
++
++ handler->close(fds[0]);
++ server.shutdown();
++}
++
++// ---------------------------------------------------------------------------
++// ANT-2026-VAMER5RC — pre-auth recover crash / force-disconnect
++// (passkey-before-recover omitted: needs PROTOCOL_VERSION bump)
++// ---------------------------------------------------------------------------
++
++TEST_CASE(
++ "ANT-2026-VAMER5RC BackedWriter recover throws instead of aborting on "
++ "client-ahead sequence",
++ "[SecurityNotice][ANT-2026-VAMER5RC][BackedIO]") {
++ class InMemorySocketHandler : public SocketHandler {
++ public:
++ int createChannel() {
++ int fd = nextFd++;
++ buffers[fd] = {};
++ return fd;
++ }
++ bool hasData(int fd) override { return !buffers[fd].empty(); }
++ ssize_t read(int fd, void* buf, size_t count) override {
++ auto& q = buffers[fd];
++ if (q.empty()) {
++ SetErrno(EPIPE);
++ return 0;
++ }
++ size_t n = std::min(count, q.size());
++ for (size_t i = 0; i < n; ++i) {
++ static_cast<char*>(buf)[i] = q.front();
++ q.pop_front();
++ }
++ return n;
++ }
++ ssize_t write(int fd, const void* buf, size_t count) override {
++ auto* c = static_cast<const char*>(buf);
++ for (size_t i = 0; i < count; ++i) {
++ buffers[fd].push_back(c[i]);
++ }
++ return count;
++ }
++ int connect(const SocketEndpoint&) override { return -1; }
++ set<int> listen(const SocketEndpoint&) override { return {}; }
++ set<int> getEndpointFds(const SocketEndpoint&) override { return {}; }
++ int accept(int) override { return -1; }
++ void stopListening(const SocketEndpoint&) override {}
++ void close(int) override {}
++ vector<int> getActiveSockets() override { return {}; }
++
++ private:
++ std::atomic<int> nextFd{1};
++ std::map<int, std::deque<char>> buffers;
++ };
++
++ auto handler = make_shared<InMemorySocketHandler>();
++ auto crypto = make_shared<CryptoHandler>("12345678901234567890123456789012",
++ 0 /*verbosity*/);
++ const int fd = handler->createChannel();
++ BackedWriter writer(handler, crypto, fd);
++ REQUIRE(writer.write(Packet(1, "one")) == BackedWriterWriteState::SUCCESS);
++ writer.invalidateSocket();
++
++ REQUIRE_THROWS_AS(writer.recover(writer.getSequenceNumber() + 1),
++ std::runtime_error);
++}
++
++TEST_CASE(
++ "ANT-2026-VAMER5RC recoverClient leaves victim socket open on bad sequence",
++ "[SecurityNotice][ANT-2026-VAMER5RC][ServerClientConnection]") {
++ auto handler = make_shared<SocketPairHandler>();
++ int live[2];
++ REQUIRE(::socketpair(AF_UNIX, SOCK_STREAM, 0, live) == 0);
++
++ const string key = "zyxwvutsrqponmlkjihgfedcba987654";
++ ServerClientConnection connection(handler, "client-recover", live[0], key);
++ REQUIRE(connection.getSocketFd() == live[0]);
++ REQUIRE(::fcntl(live[0], F_GETFD) != -1);
++
++ int attack[2];
++ REQUIRE(::socketpair(AF_UNIX, SOCK_STREAM, 0, attack) == 0);
++
++ std::thread attacker([&]() {
++ handler->readProto<SequenceHeader>(
++ attack[1], true, SocketHandler::MAX_HANDSHAKE_PROTO_LENGTH);
++ SequenceHeader bad;
++ bad.set_sequencenumber(999999);
++ handler->writeProto(attack[1], bad, true);
++ });
++
++ REQUIRE_FALSE(connection.recoverClient(attack[0]));
++ // Victim session must remain on the original fd, which must still be open.
++ REQUIRE(connection.getSocketFd() == live[0]);
++ REQUIRE(::fcntl(live[0], F_GETFD) != -1);
++
++ attacker.join();
++ connection.shutdown();
++ handler->close(live[0]);
++ handler->close(live[1]);
++ handler->close(attack[1]);
++}
++
++// ---------------------------------------------------------------------------
++// ANT-2026-AVTT7HQH — reverse-tunnel source root unlink/chown
++// ---------------------------------------------------------------------------
++
++#ifndef WIN32
++TEST_CASE(
++ "ANT-2026-AVTT7HQH createSource as user does not destroy undeletable file",
++ "[SecurityNotice][ANT-2026-AVTT7HQH][PortForwardHandler]") {
++ uid_t sessionUid = 0;
++ gid_t sessionGid = 0;
++ if (!unprivilegedTestUser(&sessionUid, &sessionGid)) {
++ SKIP("No unprivileged user available for privilege-drop test");
++ }
++
++ string dir = makeTempDir();
++ string victim = dir + "/victim_file";
++ {
++ int fd = ::open(victim.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0644);
++ REQUIRE(fd >= 0);
++ REQUIRE(::write(fd, "keepme", 6) == 6);
++ ::close(fd);
++ }
++
++ if (getuid() == 0) {
++ // Root-owned directory: after setuid to nobody, unlink must fail. This is
++ // the etserver-as-root threat model from the notice.
++ REQUIRE(::chown(dir.c_str(), 0, 0) == 0);
++ REQUIRE(::chmod(dir.c_str(), 0755) == 0);
++ REQUIRE(::chown(victim.c_str(), 0, 0) == 0);
++ } else {
++ // Non-root: remove directory write so self cannot unlink.
++ REQUIRE(::chmod(dir.c_str(), 0555) == 0);
++ }
++
++ auto networkHandler = make_shared<PipeSocketHandler>();
++ auto pipeHandler = make_shared<PipeSocketHandler>();
++ PortForwardHandler handler(networkHandler, pipeHandler, sessionUid,
++ sessionGid);
++
++ PortForwardSourceRequest request;
++ SocketEndpoint source;
++ source.set_name(victim);
++ *request.mutable_source() = source;
++ SocketEndpoint destination;
++ destination.set_port(9);
++ *request.mutable_destination() = destination;
++
++ PortForwardSourceResponse response =
++ handler.createSource(request, nullptr, sessionUid, sessionGid);
++
++ REQUIRE(response.has_error());
++
++ if (getuid() != 0) {
++ REQUIRE(::chmod(dir.c_str(), 0755) == 0);
++ }
++ struct stat st;
++ REQUIRE(::stat(victim.c_str(), &st) == 0);
++ REQUIRE(S_ISREG(st.st_mode));
++
++ ::unlink(victim.c_str());
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE(
++ "ANT-2026-AVTT7HQH createSource as user creates socket on writable path",
++ "[SecurityNotice][ANT-2026-AVTT7HQH][PortForwardHandler]") {
++ uid_t sessionUid = 0;
++ gid_t sessionGid = 0;
++ if (!unprivilegedTestUser(&sessionUid, &sessionGid)) {
++ SKIP("No unprivileged user available for privilege-drop test");
++ }
++
++ string dir = makeTempDir();
++ string sockPath = dir + "/ok.sock";
++ // Ensure the session user can create the socket in this directory.
++ REQUIRE(::chmod(dir.c_str(), 0777) == 0);
++
++ {
++ auto networkHandler = make_shared<PipeSocketHandler>();
++ auto pipeHandler = make_shared<PipeSocketHandler>();
++ PortForwardHandler handler(networkHandler, pipeHandler, sessionUid,
++ sessionGid);
++
++ PortForwardSourceRequest request;
++ SocketEndpoint source;
++ source.set_name(sockPath);
++ *request.mutable_source() = source;
++ SocketEndpoint destination;
++ destination.set_port(9);
++ *request.mutable_destination() = destination;
++
++ PortForwardSourceResponse response =
++ handler.createSource(request, nullptr, sessionUid, sessionGid);
++ REQUIRE_FALSE(response.has_error());
++
++ struct stat st;
++ REQUIRE(::stat(sockPath.c_str(), &st) == 0);
++ REQUIRE(S_ISSOCK(st.st_mode));
++ }
++
++ ::unlink(sockPath.c_str());
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE(
++ "ANT-2026-AVTT7HQH UserSocketOps listen fails on root-only path without "
++ "deleting it",
++ "[SecurityNotice][ANT-2026-AVTT7HQH][UserSocketOps]") {
++ uid_t sessionUid = 0;
++ gid_t sessionGid = 0;
++ if (!unprivilegedTestUser(&sessionUid, &sessionGid)) {
++ SKIP("No unprivileged user available for privilege-drop test");
++ }
++ if (sessionUid == 0) {
++ SKIP("Test requires a non-root session user");
++ }
++ // /dev/null is a privileged node; listen/unlink as an unprivileged user must
++ // fail and must not remove it.
++ REQUIRE(::access("/dev/null", F_OK) == 0);
++ int fd = UserSocketOps::listenUnixAsUser("/dev/null", sessionUid, sessionGid);
++ REQUIRE(fd < 0);
++ REQUIRE(::access("/dev/null", F_OK) == 0);
++}
++
++// ---------------------------------------------------------------------------
++// ANT-2026-A3WQS3AG — forward destination root connect to arbitrary unix path
++// ---------------------------------------------------------------------------
++
++TEST_CASE(
++ "ANT-2026-A3WQS3AG createDestination as session user can reach own socket",
++ "[SecurityNotice][ANT-2026-A3WQS3AG][PortForwardHandler]") {
++ uid_t sessionUid = 0;
++ gid_t sessionGid = 0;
++ if (!unprivilegedTestUser(&sessionUid, &sessionGid)) {
++ SKIP("No unprivileged user available for privilege-drop test");
++ }
++
++ string dir = makeTempDir();
++ REQUIRE(::chmod(dir.c_str(), 0777) == 0);
++ string path = dir + "/dest.sock";
++
++ int listenFd = UserSocketOps::listenUnixAsUser(path, sessionUid, sessionGid);
++ REQUIRE(listenFd >= 0);
++
++ auto networkHandler = make_shared<PipeSocketHandler>();
++ auto pipeHandler = make_shared<PipeSocketHandler>();
++ PortForwardHandler handler(networkHandler, pipeHandler, sessionUid,
++ sessionGid);
++
++ PortForwardDestinationRequest request;
++ SocketEndpoint destination;
++ destination.set_name(path);
++ *request.mutable_destination() = destination;
++ request.set_fd(7);
++
++ PortForwardDestinationResponse response = handler.createDestination(request);
++ REQUIRE_FALSE(response.has_error());
++ REQUIRE(response.has_socketid());
++
++ int accepted = ::accept(listenFd, nullptr, nullptr);
++ REQUIRE(accepted >= 0);
++ ::close(accepted);
++ ::close(listenFd);
++ ::unlink(path.c_str());
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE(
++ "ANT-2026-A3WQS3AG createDestination as session user cannot open "
++ "mode-000 socket",
++ "[SecurityNotice][ANT-2026-A3WQS3AG][PortForwardHandler]") {
++ uid_t sessionUid = 0;
++ gid_t sessionGid = 0;
++ if (!unprivilegedTestUser(&sessionUid, &sessionGid)) {
++ SKIP("No unprivileged user available for privilege-drop test");
++ }
++ if (sessionUid == 0) {
++ SKIP("Test requires a non-root session user");
++ }
++
++ string dir = makeTempDir();
++ REQUIRE(::chmod(dir.c_str(), 0777) == 0);
++ string path = dir + "/denied.sock";
++
++ // Create the listener as root (or current user), then strip access. A root
++ // connect would often still succeed; connecting after setuid to the session
++ // user must fail. Keep the listen handler alive for the whole test.
++ auto listenPipeHandler = make_shared<PipeSocketHandler>();
++ int listenFd = -1;
++ SocketEndpoint listenEp;
++ listenEp.set_name(path);
++ if (getuid() == 0) {
++ set<int> fds = listenPipeHandler->listen(listenEp);
++ REQUIRE_FALSE(fds.empty());
++ listenFd = *fds.begin();
++ } else {
++ listenFd = UserSocketOps::listenUnixAsUser(path, sessionUid, sessionGid);
++ }
++ REQUIRE(listenFd >= 0);
++ REQUIRE(::chmod(path.c_str(), 0) == 0);
++
++ auto networkHandler = make_shared<PipeSocketHandler>();
++ auto pipeHandler = make_shared<PipeSocketHandler>();
++ PortForwardHandler handler(networkHandler, pipeHandler, sessionUid,
++ sessionGid);
++
++ PortForwardDestinationRequest request;
++ SocketEndpoint destination;
++ destination.set_name(path);
++ *request.mutable_destination() = destination;
++ request.set_fd(8);
++
++ PortForwardDestinationResponse response = handler.createDestination(request);
++ REQUIRE(response.has_error());
++ REQUIRE_FALSE(response.has_socketid());
++
++ if (getuid() == 0) {
++ listenPipeHandler->stopListening(listenEp);
++ } else {
++ ::close(listenFd);
++ }
++ ::chmod(path.c_str(), 0700);
++ ::unlink(path.c_str());
++ ::rmdir(dir.c_str());
++}
++#endif
+diff --git a/test/UserSocketOpsTest.cpp b/test/UserSocketOpsTest.cpp
+new file mode 100644
+index 000000000..3012b2b05
+--- /dev/null
++++ b/test/UserSocketOpsTest.cpp
+@@ -0,0 +1,173 @@
++#include "TestHeaders.hpp"
++#include "UserSocketOps.hpp"
++
++#ifndef WIN32
++#include <sys/stat.h>
++#include <sys/un.h>
++#include <unistd.h>
++
++using namespace et;
++
++namespace {
++string makeTempDir() {
++ string dirTemplate = GetTempDirectory() + "et_user_sock_XXXXXX";
++ return string(mkdtemp(&dirTemplate[0]));
++}
++
++string longUnixPath() {
++ // sun_path is typically 108 bytes including NUL.
++ return string(sizeof(sockaddr_un::sun_path) + 8, 'x');
++}
++} // namespace
++
++TEST_CASE("UserSocketOps listen and connect as current user",
++ "[UserSocketOps]") {
++ string dir = makeTempDir();
++ string path = dir + "/sock";
++
++ uid_t uid = getuid();
++ gid_t gid = getgid();
++
++ int listenFd = UserSocketOps::listenUnixAsUser(path, uid, gid);
++ REQUIRE(listenFd >= 0);
++
++ struct stat st;
++ REQUIRE(::stat(path.c_str(), &st) == 0);
++ REQUIRE(S_ISSOCK(st.st_mode));
++
++ int connFd = UserSocketOps::connectUnixAsUser(path, uid, gid);
++ REQUIRE(connFd >= 0);
++
++ int client = ::accept(listenFd, nullptr, nullptr);
++ REQUIRE(client >= 0);
++
++ REQUIRE(::write(connFd, "ping", 4) == 4);
++ char buf[4];
++ REQUIRE(::read(client, buf, 4) == 4);
++ REQUIRE(string(buf, 4) == "ping");
++ REQUIRE(::write(client, "pong", 4) == 4);
++ REQUIRE(::read(connFd, buf, 4) == 4);
++ REQUIRE(string(buf, 4) == "pong");
++
++ ::close(client);
++ ::close(connFd);
++ ::close(listenFd);
++ ::unlink(path.c_str());
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE("UserSocketOps listenAtPath and connectAtPath in-process",
++ "[UserSocketOps]") {
++ string dir = makeTempDir();
++ string path = dir + "/sock";
++
++ int listenFd = UserSocketOps::listenAtPath(path);
++ REQUIRE(listenFd >= 0);
++
++ struct stat st;
++ REQUIRE(::stat(path.c_str(), &st) == 0);
++ REQUIRE(S_ISSOCK(st.st_mode));
++
++ int connFd = UserSocketOps::connectAtPath(path);
++ REQUIRE(connFd >= 0);
++
++ int client = ::accept(listenFd, nullptr, nullptr);
++ REQUIRE(client >= 0);
++ REQUIRE(::write(connFd, "ok", 2) == 2);
++ char buf[2];
++ REQUIRE(::read(client, buf, 2) == 2);
++ REQUIRE(string(buf, 2) == "ok");
++
++ ::close(client);
++ ::close(connFd);
++ ::close(listenFd);
++ ::unlink(path.c_str());
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE("UserSocketOps listenAtPath rejects oversized path",
++ "[UserSocketOps]") {
++ int fd = UserSocketOps::listenAtPath(longUnixPath());
++ REQUIRE(fd < 0);
++ REQUIRE(GetErrno() == ENAMETOOLONG);
++}
++
++TEST_CASE("UserSocketOps connectAtPath rejects oversized path",
++ "[UserSocketOps]") {
++ int fd = UserSocketOps::connectAtPath(longUnixPath());
++ REQUIRE(fd < 0);
++ REQUIRE(GetErrno() == ENAMETOOLONG);
++}
++
++TEST_CASE("UserSocketOps listenUnixAsUser rejects oversized path",
++ "[UserSocketOps]") {
++ int fd = UserSocketOps::listenUnixAsUser(longUnixPath(), getuid(), getgid());
++ REQUIRE(fd < 0);
++ REQUIRE(GetErrno() == ENAMETOOLONG);
++}
++
++TEST_CASE("UserSocketOps connectUnixAsUser rejects oversized path",
++ "[UserSocketOps]") {
++ int fd = UserSocketOps::connectUnixAsUser(longUnixPath(), getuid(), getgid());
++ REQUIRE(fd < 0);
++ REQUIRE(GetErrno() == ENAMETOOLONG);
++}
++
++TEST_CASE("UserSocketOps listenAtPath fails when path is a directory",
++ "[UserSocketOps]") {
++ string dir = makeTempDir();
++ // Path is itself a directory: unlink fails, bind must fail.
++ int fd = UserSocketOps::listenAtPath(dir);
++ REQUIRE(fd < 0);
++
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE("UserSocketOps connectAtPath fails when nothing listens",
++ "[UserSocketOps]") {
++ string dir = makeTempDir();
++ string path = dir + "/missing";
++ int fd = UserSocketOps::connectAtPath(path);
++ REQUIRE(fd < 0);
++
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE("UserSocketOps connectUnixAsUser fails when nothing listens",
++ "[UserSocketOps]") {
++ string dir = makeTempDir();
++ string path = dir + "/missing";
++ int fd = UserSocketOps::connectUnixAsUser(path, getuid(), getgid());
++ REQUIRE(fd < 0);
++
++ ::rmdir(dir.c_str());
++}
++
++TEST_CASE("UserSocketOps listen as user cannot unlink root-only path",
++ "[UserSocketOps]") {
++ if (getuid() == 0) {
++ SKIP("Test requires a non-root process");
++ }
++
++ // A path under /dev that a normal user cannot replace.
++ string path = "/dev/null_et_should_not_bind";
++ int fd = UserSocketOps::listenUnixAsUser(path, getuid(), getgid());
++ REQUIRE(fd < 0);
++}
++
++TEST_CASE("UserSocketOps listenAtPath replaces an existing socket path",
++ "[UserSocketOps]") {
++ string dir = makeTempDir();
++ string path = dir + "/sock";
++
++ int first = UserSocketOps::listenAtPath(path);
++ REQUIRE(first >= 0);
++ ::close(first);
++
++ int second = UserSocketOps::listenAtPath(path);
++ REQUIRE(second >= 0);
++ ::close(second);
++ ::unlink(path.c_str());
++ ::rmdir(dir.c_str());
++}
++#endif
+
+From e25b438dfedf7278661b793189fd645433cc22cd Mon Sep 17 00:00:00 2001
+From: Bryan O'Sullivan <bos@serpentine.com>
+Date: Wed, 11 Nov 2026 11:13:36 +0000
+Subject: [PATCH 02/12] fix: derive router session ownership from kernel peer
+ credentials
+
+An unprivileged local user could register a session with self-asserted uid
+and gid values. The root daemon listens on and connects to forwarded Unix
+sockets as that user, so a client claiming uid 0 could delete any file as
+root, because listening first unlinks the path, or connect to sockets that
+only root can reach, such as Docker's.
+
+Replace the supplied identity with the kernel's peer credentials on Unix,
+and reject the registration if they cannot be read, via a new
+GetPeerCredentials helper. A regression test registers forged ids and
+verifies that the connecting user's identity is stored instead.
+
+(cherry picked from commit 7d70aa2c7a33bd4805d90429762ec7330fe52855)
+
+Backport to 6.2.11: 6.2.11 has no PlatformUtils, so GetPeerCredentials is a
+file-local helper in UserTerminalRouter.cpp; the regression test is a new
+test/UserTerminalRouterTest.cpp without the 7.x test fixtures.
+
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/terminal/UserTerminalRouter.cpp | 31 ++++++++++++
+ test/UserTerminalRouterTest.cpp | 73 +++++++++++++++++++++++++++++
+ 2 files changed, 104 insertions(+)
+ create mode 100644 test/UserTerminalRouterTest.cpp
+
+diff --git a/src/terminal/UserTerminalRouter.cpp b/src/terminal/UserTerminalRouter.cpp
+index 788931cf8..fb0c9b42d 100644
+--- a/src/terminal/UserTerminalRouter.cpp
++++ b/src/terminal/UserTerminalRouter.cpp
+@@ -4,6 +4,26 @@
+ #include "ETerminal.pb.h"
+
+ namespace et {
++namespace {
++// Reads the effective uid and gid of the process at the other end of the
++// connected Unix-domain socket fd, as recorded by the kernel. Returns false if
++// the kernel cannot report them.
++bool GetPeerCredentials(int fd, uid_t* uid, gid_t* gid) {
++#ifdef __linux__
++ struct ucred cred;
++ socklen_t len = sizeof(cred);
++ if (::getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) {
++ return false;
++ }
++ *uid = cred.uid;
++ *gid = cred.gid;
++ return true;
++#else
++ return ::getpeereid(fd, uid, gid) == 0;
++#endif
++}
++} // namespace
++
+ UserTerminalRouter::UserTerminalRouter(
+ shared_ptr<PipeSocketHandler> _socketHandler,
+ const SocketEndpoint &_routerEndpoint)
+@@ -39,6 +59,17 @@ IdKeyPair UserTerminalRouter::acceptNewConnection() {
+ }
+ TerminalUserInfo tui = stringToProto<TerminalUserInfo>(packet.getPayload());
+ tui.set_fd(terminalFd);
++ // The uid/gid select the identity for privileged socket operations
++ // (UserSocketOps), so take them from the kernel, not the peer.
++ uid_t peerUid;
++ gid_t peerGid;
++ if (!GetPeerCredentials(terminalFd, &peerUid, &peerGid)) {
++ LOG(ERROR) << "Failed to read router peer credentials";
++ socketHandler->close(terminalFd);
++ return IdKeyPair({"", ""});
++ }
++ tui.set_uid(static_cast<int64_t>(peerUid));
++ tui.set_gid(static_cast<int64_t>(peerGid));
+
+ const bool inserted =
+ idInfoMap.insert(std::make_pair(tui.id(), tui)).second;
+diff --git a/test/UserTerminalRouterTest.cpp b/test/UserTerminalRouterTest.cpp
+new file mode 100644
+index 000000000..6b96481ef
+--- /dev/null
++++ b/test/UserTerminalRouterTest.cpp
+@@ -0,0 +1,73 @@
++#ifndef WIN32
++#include "ETerminal.pb.h"
++#include "PipeSocketHandler.hpp"
++#include "TestHeaders.hpp"
++#include "UserTerminalRouter.hpp"
++
++using namespace et;
++
++namespace {
++struct RouterEndpoint {
++ string directory;
++ string path;
++
++ RouterEndpoint() {
++ string tmpPath = GetTempDirectory() + string("et_test_router_XXXXXXXX");
++ directory = string(mkdtemp(&tmpPath[0]));
++ path = directory + "/router_pipe";
++ }
++
++ void cleanup(const shared_ptr<PipeSocketHandler>& socketHandler) {
++ SocketEndpoint endpoint;
++ endpoint.set_name(path);
++ socketHandler->stopListening(endpoint);
++ ::unlink(path.c_str());
++ FATAL_FAIL(::rmdir(directory.c_str()));
++ }
++};
++
++class InspectableUserTerminalRouter : public UserTerminalRouter {
++ public:
++ using UserTerminalRouter::UserTerminalRouter;
++
++ pair<int64_t, int64_t> registeredUidGid(const string& id) {
++ lock_guard<recursive_mutex> guard(routerMutex);
++ return {idInfoMap.at(id).uid(), idInfoMap.at(id).gid()};
++ }
++};
++} // namespace
++
++TEST_CASE(
++ "UserTerminalRouter overrides self-asserted uid/gid with peer "
++ "credentials",
++ "[UserTerminalRouter]") {
++ auto socketHandler = std::make_shared<PipeSocketHandler>();
++
++ RouterEndpoint testEndpoint;
++ SocketEndpoint routerEndpoint;
++ routerEndpoint.set_name(testEndpoint.path);
++ InspectableUserTerminalRouter router(socketHandler, routerEndpoint);
++
++ // Assert ids other than our own; the router must store the real ones.
++ int terminalFd = socketHandler->connect(routerEndpoint);
++ REQUIRE(terminalFd >= 0);
++ TerminalUserInfo tui;
++ tui.set_id("forged-uid-term");
++ tui.set_passkey(string(32, 'k'));
++ tui.set_uid(getuid() == 0 ? 1 : 0);
++ tui.set_gid(getgid() == 0 ? 1 : 0);
++ socketHandler->writePacket(
++ terminalFd,
++ Packet(TerminalPacketType::TERMINAL_USER_INFO, protoToString(tui)));
++
++ IdKeyPair accepted = router.acceptNewConnection();
++ REQUIRE(accepted.id == "forged-uid-term");
++ const auto [storedUid, storedGid] =
++ router.registeredUidGid("forged-uid-term");
++ REQUIRE(storedUid == static_cast<int64_t>(getuid()));
++ REQUIRE(storedGid == static_cast<int64_t>(getgid()));
++
++ socketHandler->close(terminalFd);
++ testEndpoint.cleanup(socketHandler);
++}
++#endif
+
+From 766a166e49045bf1d518ccc8bf4d9655a8f61e13 Mon Sep 17 00:00:00 2001
+From: Bryan O'Sullivan <bos@serpentine.com>
+Date: Wed, 11 Nov 2026 11:14:49 +0000
+Subject: [PATCH 03/12] fix: reject malformed router registrations without
+ aborting etserver
+
+Backport of two upstream fixes, which touch the same function:
+
+fix: reject malformed router packets without aborting etserver
+
+The router socket is intentionally reachable by local users. Sending a
+zero-length registration or a wrong packet header triggered a fatal log
+and aborted the shared daemon, disrupting all users and permitting
+repeatable service crashes.
+
+Close only the offending connection in both cases. Tests verify these
+rejections, malformed user-info protobuf, and a successful registration
+afterwards.
+
+(cherry picked from commit bbd2c5fda81731e22b84e71371a0b2cc4d89a9da)
+
+fix: reject malformed session keys before crypto initialization
+
+A local user could register a short passkey through the router, then
+connect through the legacy handshake. Crypto initialization treated the
+invalid key length as fatal and aborted the shared daemon, disconnecting
+every user.
+
+Reject router registrations unless the passkey is exactly 32 bytes and
+the id is nonempty; the server treats an empty id as no registration, so
+such an entry would be orphaned. Make the crypto constructor throw a
+connection-level error instead of aborting. Tests cover short and long
+keys, a short key or empty id at registration, and a valid registration
+afterwards.
+
+(cherry picked from commit eecfdb3b6f970ed69df1d629214f6a8d14e929a4)
+
+Backport to 6.2.11: tests ported into the new test/UserTerminalRouterTest.cpp
+without the 7.x fixtures; the malformed-protobuf case is added with the
+stringToProto fix later in this series, since 6.2.11 aborts there.
+
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/CryptoHandler.cpp | 3 +-
+ src/terminal/UserTerminalRouter.cpp | 19 ++++++-
+ test/CryptoHandlerTest.cpp | 8 +++
+ test/UserTerminalRouterTest.cpp | 84 +++++++++++++++++++++++++++++
+ 4 files changed, 111 insertions(+), 3 deletions(-)
+
+diff --git a/src/base/CryptoHandler.cpp b/src/base/CryptoHandler.cpp
+index 0637a81a4..1faa8ecd8 100644
+--- a/src/base/CryptoHandler.cpp
++++ b/src/base/CryptoHandler.cpp
+@@ -13,7 +13,8 @@ CryptoHandler::CryptoHandler(const string& _key, unsigned char nonceMSB) {
+ STFATAL << "libsodium init failed";
+ }
+ if (_key.length() != crypto_secretbox_KEYBYTES) {
+- STFATAL << "Invalid key length";
++ // Peer-supplied keys reach here; fail the connection, not the process.
++ throw std::runtime_error("Invalid key length");
+ }
+ memcpy(key, &_key[0], _key.length());
+ memset(nonce, 0, crypto_secretbox_NONCEBYTES);
+diff --git a/src/terminal/UserTerminalRouter.cpp b/src/terminal/UserTerminalRouter.cpp
+index fb0c9b42d..71d12185a 100644
+--- a/src/terminal/UserTerminalRouter.cpp
++++ b/src/terminal/UserTerminalRouter.cpp
+@@ -52,10 +52,15 @@ IdKeyPair UserTerminalRouter::acceptNewConnection() {
+ try {
+ Packet packet;
+ if (!socketHandler->readPacket(terminalFd, &packet)) {
+- STFATAL << "Missing user info packet";
++ LOG(ERROR) << "Empty router registration packet";
++ socketHandler->close(terminalFd);
++ return IdKeyPair({"", ""});
+ }
+ if (packet.getHeader() != TerminalPacketType::TERMINAL_USER_INFO) {
+- STFATAL << "Got an invalid packet header: " << int(packet.getHeader());
++ LOG(ERROR) << "Got an invalid packet header from router peer: "
++ << int(packet.getHeader());
++ socketHandler->close(terminalFd);
++ return IdKeyPair({"", ""});
+ }
+ TerminalUserInfo tui = stringToProto<TerminalUserInfo>(packet.getPayload());
+ tui.set_fd(terminalFd);
+@@ -70,6 +75,16 @@ IdKeyPair UserTerminalRouter::acceptNewConnection() {
+ }
+ tui.set_uid(static_cast<int64_t>(peerUid));
+ tui.set_gid(static_cast<int64_t>(peerGid));
++ if (tui.id().empty() || tui.passkey().size() != crypto_secretbox_KEYBYTES) {
++ // The router socket is world-connectable, so registration input is
++ // untrusted; a malformed credential must be dropped here rather than
++ // aborting the daemon later when the key reaches the crypto layer.
++ LOG(ERROR) << "Rejecting terminal registration with invalid "
++ "id/passkey length: "
++ << tui.id().size() << "/" << tui.passkey().size();
++ socketHandler->close(terminalFd);
++ return IdKeyPair({"", ""});
++ }
+
+ const bool inserted =
+ idInfoMap.insert(std::make_pair(tui.id(), tui)).second;
+diff --git a/test/CryptoHandlerTest.cpp b/test/CryptoHandlerTest.cpp
+index f177ff9b3..51a48ef5f 100644
+--- a/test/CryptoHandlerTest.cpp
++++ b/test/CryptoHandlerTest.cpp
+@@ -13,3 +13,11 @@ TEST_CASE("DoesEncryptDecrypt", "[CryptoHandler]") {
+ string decryptedMessage = decryptHandler->decrypt(encryptedMessage);
+ REQUIRE(message == decryptedMessage);
+ }
++
++TEST_CASE("Constructor rejects wrong-length keys", "[CryptoHandler]") {
++ REQUIRE_THROWS_AS(CryptoHandler("short", 0), std::runtime_error);
++ REQUIRE_THROWS_AS(
++ CryptoHandler(string(crypto_secretbox_KEYBYTES + 1, 'k'), 0),
++ std::runtime_error);
++ REQUIRE_NOTHROW(CryptoHandler("12345678901234567890123456789012", 0));
++}
+diff --git a/test/UserTerminalRouterTest.cpp b/test/UserTerminalRouterTest.cpp
+index 6b96481ef..66e4c2980 100644
+--- a/test/UserTerminalRouterTest.cpp
++++ b/test/UserTerminalRouterTest.cpp
+@@ -35,6 +35,22 @@ class InspectableUserTerminalRouter : public UserTerminalRouter {
+ return {idInfoMap.at(id).uid(), idInfoMap.at(id).gid()};
+ }
+ };
++
++// Registers a fake terminal with the given credentials and returns its fd.
++int registerFakeTerminal(shared_ptr<PipeSocketHandler> socketHandler,
++ UserTerminalRouter& router,
++ const SocketEndpoint& routerEndpoint, const string& id,
++ const string& passkey, IdKeyPair* accepted) {
++ int fd = socketHandler->connect(routerEndpoint);
++ REQUIRE(fd >= 0);
++ TerminalUserInfo tui;
++ tui.set_id(id);
++ tui.set_passkey(passkey);
++ socketHandler->writePacket(
++ fd, Packet(TerminalPacketType::TERMINAL_USER_INFO, protoToString(tui)));
++ *accepted = router.acceptNewConnection();
++ return fd;
++}
+ } // namespace
+
+ TEST_CASE(
+@@ -70,4 +86,72 @@ TEST_CASE(
+ socketHandler->close(terminalFd);
+ testEndpoint.cleanup(socketHandler);
+ }
++
++TEST_CASE("UserTerminalRouter rejects malformed registration packets",
++ "[UserTerminalRouter]") {
++ // Each malformed packet must cost only the offending connection.
++ auto socketHandler = std::make_shared<PipeSocketHandler>();
++
++ RouterEndpoint testEndpoint;
++ SocketEndpoint routerEndpoint;
++ routerEndpoint.set_name(testEndpoint.path);
++ InspectableUserTerminalRouter router(socketHandler, routerEndpoint);
++
++ // Zero-length packet: an 8-byte zero length prefix.
++ int fdZero = socketHandler->connect(routerEndpoint);
++ REQUIRE(fdZero >= 0);
++ const int64_t zero = 0;
++ socketHandler->writeAllOrThrow(fdZero, &zero, sizeof(zero), false);
++ IdKeyPair accepted = router.acceptNewConnection();
++ REQUIRE(accepted.id.empty());
++ REQUIRE(accepted.key.empty());
++
++ // Wrong packet header: valid framing, header is not TERMINAL_USER_INFO.
++ int fdHeader = socketHandler->connect(routerEndpoint);
++ REQUIRE(fdHeader >= 0);
++ socketHandler->writePacket(
++ fdHeader, Packet(TerminalPacketType::TERMINAL_BUFFER, "junk"));
++ accepted = router.acceptNewConnection();
++ REQUIRE(accepted.id.empty());
++ REQUIRE(accepted.key.empty());
++
++ // The router still accepts a valid registration afterwards.
++ int fdOk = registerFakeTerminal(socketHandler, router, routerEndpoint,
++ "still-alive", string(32, 'k'), &accepted);
++ REQUIRE(accepted.id == "still-alive");
++ socketHandler->close(fdZero);
++ socketHandler->close(fdHeader);
++ socketHandler->close(fdOk);
++ testEndpoint.cleanup(socketHandler);
++}
++
++TEST_CASE("UserTerminalRouter rejects registrations with invalid credentials",
++ "[UserTerminalRouter]") {
++ auto socketHandler = std::make_shared<PipeSocketHandler>();
++
++ RouterEndpoint testEndpoint;
++ SocketEndpoint routerEndpoint;
++ routerEndpoint.set_name(testEndpoint.path);
++ InspectableUserTerminalRouter router(socketHandler, routerEndpoint);
++
++ IdKeyPair accepted;
++ int fdShort = registerFakeTerminal(socketHandler, router, routerEndpoint,
++ "short-key", "short", &accepted);
++ REQUIRE(accepted.id.empty());
++ int fdLong = registerFakeTerminal(socketHandler, router, routerEndpoint,
++ "long-key", string(33, 'k'), &accepted);
++ REQUIRE(accepted.id.empty());
++ int fdEmptyId = registerFakeTerminal(socketHandler, router, routerEndpoint,
++ "", string(32, 'k'), &accepted);
++ REQUIRE(accepted.id.empty());
++ int fdOk = registerFakeTerminal(socketHandler, router, routerEndpoint,
++ "valid", string(32, 'k'), &accepted);
++ REQUIRE(accepted.id == "valid");
++
++ socketHandler->close(fdShort);
++ socketHandler->close(fdLong);
++ socketHandler->close(fdEmptyId);
++ socketHandler->close(fdOk);
++ testEndpoint.cleanup(socketHandler);
++}
+ #endif
+
+From bb48c3c44b214d83d80fb4a63088e5e4c78079c2 Mon Sep 17 00:00:00 2001
+From: Bryan O'Sullivan <bos@serpentine.com>
+Date: Wed, 11 Nov 2026 11:16:58 +0000
+Subject: [PATCH 04/12] fix: reject malformed session packets without aborting
+ etserver
+
+Backport of the upstream fixes that turn peer-triggered fatal errors on
+session packets into per-connection errors. In 6.2.11 each of these
+aborts the root daemon and ends every user's sessions:
+
+- frame lengths below the packet header, and ciphertext shorter than its
+ authentication tag (4545da51a)
+- a packet that fails authentication: 6.2.11 calls STFATAL; upstream
+ made it throw in 540367ac4 (#793), and de5dbd9b9 advances the nonce
+ only for authentic packets so the session can recover
+- unencrypted frames, an unexpected first header, and unparsable
+ protobuf payloads (46319d9e9)
+- unexpected packet types from the client (651fe3e71)
+
+(cherry picked from commit 4545da51aed065801162dd9f02a81374284e2e66)
+(cherry picked from commit 46319d9e9302b459b57ee18e4d1a58dfb5d0c785)
+(cherry picked from commit 651fe3e717305240643a6201422dd9baeaacb867)
+(cherry picked from commit de5dbd9b9df68a7fbd1813adad9eff871d8a50bf)
+Refs: 540367ac4509be41714769cf511d8c0aa90cde7a (decrypt part only)
+
+Backport to 6.2.11: server side only; the client keeps 6.2.11's
+behaviour. 6.2.11's per-connection thread has no exception handler, so
+an exception escaping it would still terminate the daemon: wrap
+TerminalServer::handleConnection like upstream does, ending only that
+session. Tests are a new test/MalformedPacketTest.cpp and a
+malformed-protobuf case in test/UserTerminalRouterTest.cpp, since
+upstream's BackedIOTest fixtures are not in 6.2.11.
+
+Co-authored-by: Jason Gauci <jgmath2000@gmail.com>
+Co-authored-by: Eric Psalmond <epsalmond@users.noreply.github.com>
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/BackedReader.cpp | 24 ++++++++--
+ src/base/Connection.cpp | 10 +++-
+ src/base/CryptoHandler.cpp | 11 ++++-
+ src/base/Headers.hpp | 10 +++-
+ src/base/Packet.hpp | 12 +++--
+ src/terminal/TerminalServer.cpp | 48 ++++++++++++-------
+ test/MalformedPacketTest.cpp | 82 +++++++++++++++++++++++++++++++++
+ test/UserTerminalRouterTest.cpp | 11 +++++
+ 8 files changed, 182 insertions(+), 26 deletions(-)
+ create mode 100644 test/MalformedPacketTest.cpp
+
+diff --git a/src/base/BackedReader.cpp b/src/base/BackedReader.cpp
+index f93b7c432..3ec0c092e 100644
+--- a/src/base/BackedReader.cpp
++++ b/src/base/BackedReader.cpp
+@@ -32,10 +32,19 @@ int BackedReader::read(Packet* packet) {
+
+ if (localBuffer.size() > 0) {
+ VLOG(1) << "Reading from local buffer";
+- *packet = Packet(localBuffer.front());
++ try {
++ Packet next(localBuffer.front());
++ next.decrypt(cryptoHandler);
++ *packet = next;
++ } catch (const MalformedPacketError&) {
++ // revive() counted these entries as received. Uncount them so the next
++ // recovery asks the peer to resend them.
++ sequenceNumber -= localBuffer.size();
++ localBuffer.clear();
++ throw;
++ }
+ localBuffer.pop_front();
+ VLOG(1) << "New local buffer size: " << localBuffer.size();
+- packet->decrypt(cryptoHandler);
+ return 1;
+ }
+
+@@ -65,11 +74,20 @@ int BackedReader::read(Packet* packet) {
+ return 0;
+ }
+ int messageLength = getPartialMessageLength();
++ // Reject impossible or oversized lengths before allocating. EPIPE severs
++ // only this socket, so the session can reconnect.
++ if (messageLength < Packet::HEADER_SIZE ||
++ messageLength > SocketHandler::DEFAULT_MAX_PROTO_LENGTH) {
++ LOG(ERROR) << "Rejecting out-of-bounds framed length: " << messageLength;
++ SetErrno(EPIPE);
++ return -1;
++ }
+ VLOG(2) << "Reading message of length: " << messageLength;
+ int messageRemainder = messageLength - (partialMessage.length() - 4);
+ if (messageRemainder) {
+ VLOG(2) << "bytes remaining: " << messageRemainder;
+- string s(messageRemainder, '\0');
++ // Allocate per read, not for the whole declared length.
++ string s(std::min(messageRemainder, 64 * 1024), '\0');
+ ssize_t bytesRead = socketHandler->read(socketFd, &s[0], s.length());
+ if (bytesRead == 0) {
+ // Connection is closed. Instead of closing the socket, set EPIPE.
+diff --git a/src/base/Connection.cpp b/src/base/Connection.cpp
+index 2c7859c07..943342457 100644
+--- a/src/base/Connection.cpp
++++ b/src/base/Connection.cpp
+@@ -152,7 +152,15 @@ bool Connection::read(Packet* packet) {
+ VLOG(4) << "Before read get connectionMutex";
+ lock_guard<std::recursive_mutex> guard(connectionMutex);
+ VLOG(4) << "After read get connectionMutex";
+- ssize_t messagesRead = reader->read(packet);
++ ssize_t messagesRead;
++ try {
++ messagesRead = reader->read(packet);
++ } catch (const MalformedPacketError& ex) {
++ // The reader has not counted the packet, so recovery resends it.
++ LOG(WARNING) << "Reconnecting after a rejected packet: " << ex.what();
++ closeSocketAndMaybeReconnect();
++ return false;
++ }
+ auto localErrno = GetErrno();
+ if (messagesRead == -1) {
+ if (isSkippableError(localErrno)) {
+diff --git a/src/base/CryptoHandler.cpp b/src/base/CryptoHandler.cpp
+index 1faa8ecd8..8cbc02276 100644
+--- a/src/base/CryptoHandler.cpp
++++ b/src/base/CryptoHandler.cpp
+@@ -34,13 +34,22 @@ string CryptoHandler::encrypt(const string& buffer) {
+ }
+
+ string CryptoHandler::decrypt(const string& buffer) {
++ if (buffer.length() < crypto_secretbox_MACBYTES) {
++ throw MalformedPacketError(
++ "Ciphertext shorter than the authentication tag");
++ }
+ lock_guard<std::mutex> guard(cryptoMutex);
++ // Advance the nonce only for an authentic packet, so a rejected one leaves
++ // this side in step with the sender for the retransmission.
++ unsigned char savedNonce[crypto_secretbox_NONCEBYTES];
++ memcpy(savedNonce, nonce, sizeof(nonce));
+ incrementNonce();
+ string retval(buffer.length() - crypto_secretbox_MACBYTES, '\0');
+ if (crypto_secretbox_open_easy((unsigned char*)&retval[0],
+ (const unsigned char*)buffer.c_str(),
+ buffer.length(), nonce, key) == -1) {
+- STFATAL << "Decrypt failed. Possible key mismatch?";
++ memcpy(nonce, savedNonce, sizeof(nonce));
++ throw MalformedPacketError("Decrypt failed. Possible key mismatch?");
+ }
+ return retval;
+ }
+diff --git a/src/base/Headers.hpp b/src/base/Headers.hpp
+index 2a707767b..49279c410 100644
+--- a/src/base/Headers.hpp
++++ b/src/base/Headers.hpp
+@@ -316,11 +316,19 @@ inline int replaceAll(std::string& str, const std::string& from,
+ return retval;
+ }
+
++// A peer sent a packet that fails authentication, has an unexpected type, or
++// has an unparsable payload.
++class MalformedPacketError : public std::runtime_error {
++ public:
++ using std::runtime_error::runtime_error;
++};
++
+ template <typename T>
+ inline T stringToProto(const string& s) {
+ T t;
+ if (!t.ParseFromString(s)) {
+- STFATAL << "Error parsing string to proto: " << s.length() << " " << s;
++ // Payloads come from peers; let the connection's handler reject them.
++ throw MalformedPacketError("Error parsing " + string(t.GetTypeName()));
+ }
+ return t;
+ }
+diff --git a/src/base/Packet.hpp b/src/base/Packet.hpp
+index ed699447a..e222c3617 100644
+--- a/src/base/Packet.hpp
++++ b/src/base/Packet.hpp
+@@ -13,9 +13,12 @@ class Packet {
+ Packet(bool _encrypted, uint8_t _header, const string& _payload)
+ : encrypted(_encrypted), header(_header), payload(_payload) {}
+ explicit Packet(const string& serializedPacket) {
++ if (serializedPacket.size() < HEADER_SIZE) {
++ throw MalformedPacketError("Serialized packet shorter than its header");
++ }
+ encrypted = serializedPacket[0];
+ header = serializedPacket[1];
+- payload = serializedPacket.substr(2);
++ payload = serializedPacket.substr(HEADER_SIZE);
+ }
+
+ void decrypt(shared_ptr<CryptoHandler> cryptoHandler) {
+@@ -23,7 +26,9 @@ class Packet {
+ encrypted = false;
+ payload = cryptoHandler->decrypt(payload);
+ } else {
+- STFATAL << "Tried to decrypt a packet that wasn't encrypted";
++ // Peer-controlled framing: sever this connection, not the process.
++ throw MalformedPacketError(
++ "Received an unencrypted packet on an encrypted connection");
+ }
+ }
+
+@@ -49,8 +54,9 @@ class Packet {
+ return s;
+ }
+
+- protected:
+ static const int HEADER_SIZE = 2;
++
++ protected:
+ bool encrypted;
+ uint8_t header;
+
+diff --git a/src/terminal/TerminalServer.cpp b/src/terminal/TerminalServer.cpp
+index cbf90f284..44a22c648 100644
+--- a/src/terminal/TerminalServer.cpp
++++ b/src/terminal/TerminalServer.cpp
+@@ -370,7 +370,11 @@ void TerminalServer::runTerminal(
+ break;
+ }
+ default:
+- STFATAL << "Unknown packet type: " << int(packetType);
++ LOG(WARNING) << "Rejecting untrusted packet type from client: "
++ << int(packetType) << "; closing connection";
++ serverClientState->closeSocket();
++ run = false;
++ break;
+ }
+ }
+ }
+@@ -394,22 +398,32 @@ void TerminalServer::runTerminal(
+
+ void TerminalServer::handleConnection(
+ shared_ptr<ServerClientConnection> serverClientState) {
+- Packet packet;
+- while (!serverClientState->readPacket(&packet)) {
+- LOG(INFO) << "Waiting for initial packet...";
+- sleep(1);
+- }
+- if (packet.getHeader() != EtPacketType::INITIAL_PAYLOAD) {
+- STFATAL << "Invalid header: expecting INITIAL_PAYLOAD but got "
+- << packet.getHeader();
+- }
+- InitialPayload payload = stringToProto<InitialPayload>(packet.getPayload());
+- if (payload.jumphost()) {
+- LOG(INFO) << "RUNNING JUMPHOST";
+- runJumpHost(serverClientState, payload);
+- } else {
+- LOG(INFO) << "RUNNING TERMINAL";
+- runTerminal(serverClientState, payload);
++ // Runs on its own thread: an exception escaping it would terminate the
++ // daemon, so peer-triggered errors end only this session.
++ try {
++ Packet packet;
++ while (!serverClientState->readPacket(&packet)) {
++ LOG(INFO) << "Waiting for initial packet...";
++ sleep(1);
++ }
++ if (packet.getHeader() != EtPacketType::INITIAL_PAYLOAD) {
++ throw std::runtime_error("Expected INITIAL_PAYLOAD but got header " +
++ to_string(int(packet.getHeader())));
++ }
++ InitialPayload payload = stringToProto<InitialPayload>(packet.getPayload());
++ if (payload.jumphost()) {
++ LOG(INFO) << "RUNNING JUMPHOST";
++ runJumpHost(serverClientState, payload);
++ } else {
++ LOG(INFO) << "RUNNING TERMINAL";
++ runTerminal(serverClientState, payload);
++ }
++ } catch (const std::exception &ex) {
++ LOG(ERROR) << "Terminal thread failed: " << ex.what();
++ serverClientState->closeSocket();
++ string id = serverClientState->getId();
++ serverClientState.reset();
++ removeClient(id);
+ }
+ }
+
+diff --git a/test/MalformedPacketTest.cpp b/test/MalformedPacketTest.cpp
+new file mode 100644
+index 000000000..c60a9c285
+--- /dev/null
++++ b/test/MalformedPacketTest.cpp
+@@ -0,0 +1,82 @@
++// Backported regression tests for malformed and unauthenticated session
++// packets. Upstream keeps these in test/unit_tests/BackedIOTest.cpp, which
++// relies on fixtures 6.2.11 does not have.
++
++#include <sys/socket.h>
++
++#include "BackedReader.hpp"
++#include "CryptoHandler.hpp"
++#include "ETerminal.pb.h"
++#include "Packet.hpp"
++#include "PipeSocketHandler.hpp"
++#include "TestHeaders.hpp"
++
++using namespace et;
++
++namespace {
++const string kKey = "12345678901234567890123456789012";
++}
++
++TEST_CASE("CryptoHandler rejects ciphertext shorter than the tag",
++ "[MalformedPacket]") {
++ CryptoHandler receiver(kKey, 0);
++ REQUIRE_THROWS_AS(receiver.decrypt("short"), MalformedPacketError);
++}
++
++TEST_CASE("CryptoHandler keeps its nonce after rejecting a ciphertext",
++ "[MalformedPacket]") {
++ CryptoHandler sender(kKey, 0);
++ CryptoHandler receiver(kKey, 0);
++ const string first = sender.encrypt("first");
++ const string second = sender.encrypt("second");
++
++ string tampered = first;
++ tampered.back() ^= 1;
++ REQUIRE_THROWS_AS(receiver.decrypt(tampered), MalformedPacketError);
++ REQUIRE(receiver.decrypt(first) == "first");
++ REQUIRE(receiver.decrypt(second) == "second");
++}
++
++TEST_CASE("Packet rejects malformed serializations", "[MalformedPacket]") {
++ REQUIRE_THROWS_AS(Packet(string("x")), MalformedPacketError);
++
++ Packet plain(1, "payload");
++ auto crypto = make_shared<CryptoHandler>(kKey, 0);
++ REQUIRE_THROWS_AS(plain.decrypt(crypto), MalformedPacketError);
++}
++
++TEST_CASE("stringToProto rejects unparsable payloads", "[MalformedPacket]") {
++ REQUIRE_THROWS_AS(stringToProto<TerminalUserInfo>("junk"),
++ MalformedPacketError);
++}
++
++TEST_CASE("BackedReader uncounts catchup after rejecting an entry",
++ "[MalformedPacket]") {
++ int fds[2];
++ REQUIRE(::socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
++ auto handler = make_shared<PipeSocketHandler>();
++ auto sender = make_shared<CryptoHandler>(kKey, 0);
++ BackedReader reader(handler, make_shared<CryptoHandler>(kKey, 0), fds[0]);
++
++ Packet first(1, "first");
++ first.encrypt(sender);
++ Packet second(2, "second");
++ second.encrypt(sender);
++ string tampered = first.serialize();
++ tampered.back() ^= 1;
++
++ reader.revive(fds[0], {tampered, second.serialize()});
++ Packet out;
++ REQUIRE_THROWS_AS(reader.read(&out), MalformedPacketError);
++ REQUIRE(reader.getSequenceNumber() == 0);
++
++ reader.revive(fds[0], {first.serialize(), second.serialize()});
++ REQUIRE(reader.read(&out) == 1);
++ REQUIRE(out.getPayload() == "first");
++ REQUIRE(reader.read(&out) == 1);
++ REQUIRE(out.getPayload() == "second");
++ REQUIRE(reader.getSequenceNumber() == 2);
++
++ ::close(fds[0]);
++ ::close(fds[1]);
++}
+diff --git a/test/UserTerminalRouterTest.cpp b/test/UserTerminalRouterTest.cpp
+index 66e4c2980..9d5ab7bda 100644
+--- a/test/UserTerminalRouterTest.cpp
++++ b/test/UserTerminalRouterTest.cpp
+@@ -115,12 +115,23 @@ TEST_CASE("UserTerminalRouter rejects malformed registration packets",
+ REQUIRE(accepted.id.empty());
+ REQUIRE(accepted.key.empty());
+
++ // TERMINAL_USER_INFO-framed packet whose payload is not valid protobuf
++ // ("junk" = field 13, wire type 2, length 117 with 2 bytes remaining).
++ int fdProto = socketHandler->connect(routerEndpoint);
++ REQUIRE(fdProto >= 0);
++ socketHandler->writePacket(
++ fdProto, Packet(TerminalPacketType::TERMINAL_USER_INFO, "junk"));
++ accepted = router.acceptNewConnection();
++ REQUIRE(accepted.id.empty());
++ REQUIRE(accepted.key.empty());
++
+ // The router still accepts a valid registration afterwards.
+ int fdOk = registerFakeTerminal(socketHandler, router, routerEndpoint,
+ "still-alive", string(32, 'k'), &accepted);
+ REQUIRE(accepted.id == "still-alive");
+ socketHandler->close(fdZero);
+ socketHandler->close(fdHeader);
++ socketHandler->close(fdProto);
+ socketHandler->close(fdOk);
+ testEndpoint.cleanup(socketHandler);
+ }
+
+From 220b6c4b741986dd8335b7a42ff2e450fb66fd75 Mon Sep 17 00:00:00 2001
+From: psaab <ps@mu.org>
+Date: Wed, 11 Nov 2026 11:17:27 +0000
+Subject: [PATCH 05/12] base: Fix etserver crash on transient accept() errors
+ (#756)
+
+* base: Fix etserver crash on transient accept() errors
+
+UnixSocketHandler::accept() called FATAL_FAIL on any accept() errno
+other than EAGAIN/EWOULDBLOCK, aborting the entire server. accept(2)
+routinely returns benign per-connection errors -- notably ECONNABORTED
+(the peer reset the connection before we accepted it) and EINTR. These
+are surfaced readily on FreeBSD by clients that connect and immediately
+disconnect (keepalive/reconnect churn), crashing etserver.
+
+Treat EAGAIN, EWOULDBLOCK, ECONNABORTED, and EINTR as non-fatal and
+return -1; the accept loop already handles this by retrying. Genuinely
+unexpected errnos still fail fatally.
+
+Backtrace on FreeBSD:
+
+ #0 thr_kill () at thr_kill.S:4
+ #1 __raise (s=s@entry=6) at /usr/src/lib/libc/gen/raise.c:50
+ #2 abort () at /usr/src/lib/libc/stdlib/abort.c:64
+ #3 el::base::utils::abort (status=1, reason="Fatal log at [.../src/base/UnixSocketHandler.cpp:146] ...")
+ at external_imported/easyloggingpp/src/easylogging++.cc:125
+ #4 el::base::Writer::triggerDispatch () at external_imported/easyloggingpp/src/easylogging++.cc:2653
+ #5 el::base::Writer::processDispatch () at external_imported/easyloggingpp/src/easylogging++.cc:2616
+ #6 el::base::Writer::~Writer () at external_imported/easyloggingpp/src/easylogging++.h:3209
+ #7 et::UnixSocketHandler::accept (this=..., sockFd=10) at src/base/UnixSocketHandler.cpp:146
+ #8 et::ServerConnection::acceptNewConnection (this=..., fd=10) at src/base/ServerConnection.cpp:17
+ #9 et::TerminalServer::run (this=...) at src/terminal/TerminalServer.cpp:79
+ #10 main (argc=6, argv=...) at src/terminal/TerminalServerMain.cpp:203
+
+* test: Cover accept() transient-error handling
+
+Add unit tests for UnixSocketHandler::isTransientAcceptError(), the helper
+that decides which accept() errnos are recoverable. This exercises the
+ECONNABORTED and EINTR cases (the FreeBSD crash) directly, plus EAGAIN/
+EWOULDBLOCK, and confirms genuine errors (EBADF, EINVAL, ...) stay fatal.
+
+Also add an end-to-end check that accept() on a non-blocking listening
+socket with no pending connection returns -1 instead of aborting.
+(cherry picked from commit c6650d9577f50317af197d1b1dd3e7b3cb2fc749)
+
+Backport to 6.2.11: conflict only in header comments; no tests, since
+upstream added none with this change.
+
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/UnixSocketHandler.cpp | 18 +++++++++++++++++-
+ src/base/UnixSocketHandler.hpp | 6 ++++++
+ 2 files changed, 23 insertions(+), 1 deletion(-)
+
+diff --git a/src/base/UnixSocketHandler.cpp b/src/base/UnixSocketHandler.cpp
+index 21f742b18..223235cd0 100644
+--- a/src/base/UnixSocketHandler.cpp
++++ b/src/base/UnixSocketHandler.cpp
+@@ -142,7 +142,10 @@ int UnixSocketHandler::accept(int sockFd) {
+ initSocket(client_sock);
+ VLOG(3) << "Client_socket inserted to activeSockets";
+ return client_sock;
+- } else if (acceptErrno != EAGAIN && acceptErrno != EWOULDBLOCK) {
++ } else if (isTransientAcceptError(acceptErrno)) {
++ // Transient, per-connection failure: fall through and return -1; the
++ // server loop simply retries on the next iteration.
++ } else {
+ FATAL_FAIL(-1); // STFATAL with the error
+ }
+
+@@ -150,6 +153,19 @@ int UnixSocketHandler::accept(int sockFd) {
+ return -1;
+ }
+
++bool UnixSocketHandler::isTransientAcceptError(int err) {
++ // accept(2) routinely fails for benign, per-connection reasons that must
++ // not abort the whole server:
++ // - EAGAIN/EWOULDBLOCK: non-blocking socket with no pending connection.
++ // - ECONNABORTED: the peer reset the connection between landing in the
++ // listen queue and our accept() call. Surfaced readily on FreeBSD by
++ // clients that connect and immediately disconnect (keepalive/reconnect
++ // churn) and previously aborted etserver.
++ // - EINTR: the call was interrupted by a signal.
++ return err == EAGAIN || err == EWOULDBLOCK || err == ECONNABORTED ||
++ err == EINTR;
++}
++
+ void UnixSocketHandler::close(int fd) {
+ lock_guard<std::recursive_mutex> globalGuard(globalMutex);
+ if (fd == -1) {
+diff --git a/src/base/UnixSocketHandler.hpp b/src/base/UnixSocketHandler.hpp
+index d94679503..c9955226f 100644
+--- a/src/base/UnixSocketHandler.hpp
++++ b/src/base/UnixSocketHandler.hpp
+@@ -14,6 +14,12 @@ class UnixSocketHandler : public SocketHandler {
+ virtual ssize_t read(int fd, void* buf, size_t count);
+ virtual ssize_t write(int fd, const void* buf, size_t count);
+ virtual int accept(int fd);
++ /**
++ * @brief Returns true if an accept() errno is a transient, per-connection
++ * failure that must be reported to the caller rather than aborting the
++ * server (EAGAIN/EWOULDBLOCK, ECONNABORTED, EINTR).
++ */
++ static bool isTransientAcceptError(int err);
+ virtual void close(int fd);
+ virtual vector<int> getActiveSockets();
+
+
+From f98cf16dbcbb6728a0b17fa00ab52337d47ec5df Mon Sep 17 00:00:00 2001
+From: Bryan O'Sullivan <bos@serpentine.com>
+Date: Wed, 11 Nov 2026 11:17:59 +0000
+Subject: [PATCH 06/12] fix: survive accept resource exhaustion and cap pending
+ handshakes
+
+Compatibility: connections beyond 64 queued or active handshakes are
+closed on arrival until slots free up. A flood of silent connections now
+refuses new sessions for its duration instead of aborting the daemon.
+
+Unauthenticated peers could open silent TCP connections faster than the
+handshake worker pool drained them. Exhausting descriptors made accept log
+a fatal error and abort the shared daemon, disconnecting every user.
+
+Treat descriptor and kernel-memory exhaustion from accept as retryable,
+pausing briefly so the still-readable listener does not spin the loop.
+Allow at most 64 queued or active handshakes. Tests cover the error
+classification and refusal at the cap.
+
+(cherry picked from commit c0e36f21ea5967d10a3e4cd937a418e3057fc6b1)
+
+Backport to 6.2.11: conflicts only in comments and context; the Windows
+WSAEMFILE mapping is left out. The error classification tests for this and
+the previous commit are in a new test/AcceptErrorTest.cpp; the pending-cap
+test needs fixtures 6.2.11 does not have.
+
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/ServerConnection.cpp | 15 +++++++++++++--
+ src/base/ServerConnection.hpp | 9 +++++++++
+ src/base/UnixSocketHandler.cpp | 14 ++++++++++++++
+ src/base/UnixSocketHandler.hpp | 3 +++
+ test/AcceptErrorTest.cpp | 23 +++++++++++++++++++++++
+ 5 files changed, 62 insertions(+), 2 deletions(-)
+ create mode 100644 test/AcceptErrorTest.cpp
+
+diff --git a/src/base/ServerConnection.cpp b/src/base/ServerConnection.cpp
+index e91d4bb13..4a0c4841a 100644
+--- a/src/base/ServerConnection.cpp
++++ b/src/base/ServerConnection.cpp
+@@ -20,8 +20,19 @@ bool ServerConnection::acceptNewConnection(int fd) {
+ }
+ VLOG(1) << "SERVER: got client socket fd: " << clientSocketFd;
+ lock_guard<std::recursive_mutex> guard(classMutex);
+- clientHandlerThreadPool->enqueue(
+- [this, clientSocketFd]() { this->clientHandler(clientSocketFd); });
++ // Unauthenticated peers can hold handshakes open; bound the descriptors
++ // they retain.
++ if (pendingHandshakes >= MAX_PENDING_HANDSHAKES) {
++ LOG_EVERY_N(100, WARNING) << "Too many pending handshakes; refusing";
++ socketHandler->close(clientSocketFd);
++ return false;
++ }
++ ++pendingHandshakes;
++ clientHandlerThreadPool->enqueue([this, clientSocketFd]() {
++ this->clientHandler(clientSocketFd);
++ lock_guard<std::recursive_mutex> g(classMutex);
++ --pendingHandshakes;
++ });
+ return true;
+ }
+
+diff --git a/src/base/ServerConnection.hpp b/src/base/ServerConnection.hpp
+index f7c937c9a..03f460cae 100644
+--- a/src/base/ServerConnection.hpp
++++ b/src/base/ServerConnection.hpp
+@@ -13,6 +13,13 @@ struct IdKeyPair {
+
+ class ServerConnection {
+ public:
++ /**
++ * @brief Maximum connections queued for or inside clientHandler; further
++ * connections are closed on arrival. A slot frees when clientHandler
++ * returns; queued connections wait for a pool worker with no deadline.
++ */
++ static constexpr int MAX_PENDING_HANDSHAKES = 64;
++
+ explicit ServerConnection(std::shared_ptr<SocketHandler> socketHandler,
+ const SocketEndpoint& _serverEndpoint);
+
+@@ -57,6 +64,8 @@ class ServerConnection {
+ shared_ptr<ServerClientConnection> serverClientState) = 0;
+
+ protected:
++ /** @brief Connections currently inside clientHandler's handshake stage. */
++ int pendingHandshakes = 0;
+ void destroyPartialConnection(const string& clientId);
+
+ shared_ptr<SocketHandler> socketHandler;
+diff --git a/src/base/UnixSocketHandler.cpp b/src/base/UnixSocketHandler.cpp
+index 223235cd0..57f333fac 100644
+--- a/src/base/UnixSocketHandler.cpp
++++ b/src/base/UnixSocketHandler.cpp
+@@ -132,6 +132,16 @@ int UnixSocketHandler::accept(int sockFd) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ }
+
++ if (client_sock < 0 && isResourceExhausted(acceptErrno)) {
++ // The connection stays queued until descriptors free up, so the listener
++ // remains readable; pause briefly rather than spin or abort. Sleep
++ // without globalMutex, which session I/O needs.
++ LOG_EVERY_N(100, ERROR) << "Accept deferred: " << strerror(acceptErrno);
++ std::this_thread::sleep_for(std::chrono::milliseconds(10));
++ SetErrno(acceptErrno);
++ return -1;
++ }
++
+ lock_guard<std::recursive_mutex> guard(globalMutex);
+ if (client_sock >= 0) {
+ VLOG(3) << "Socket " << sockFd
+@@ -153,6 +163,10 @@ int UnixSocketHandler::accept(int sockFd) {
+ return -1;
+ }
+
++bool UnixSocketHandler::isResourceExhausted(int err) {
++ return err == EMFILE || err == ENFILE || err == ENOMEM || err == ENOBUFS;
++}
++
+ bool UnixSocketHandler::isTransientAcceptError(int err) {
+ // accept(2) routinely fails for benign, per-connection reasons that must
+ // not abort the whole server:
+diff --git a/src/base/UnixSocketHandler.hpp b/src/base/UnixSocketHandler.hpp
+index c9955226f..86976b295 100644
+--- a/src/base/UnixSocketHandler.hpp
++++ b/src/base/UnixSocketHandler.hpp
+@@ -20,6 +20,9 @@ class UnixSocketHandler : public SocketHandler {
+ * server (EAGAIN/EWOULDBLOCK, ECONNABORTED, EINTR).
+ */
+ static bool isTransientAcceptError(int err);
++ /** @brief True when accept(2) failed because descriptors or kernel memory
++ * ran out (EMFILE/ENFILE/ENOMEM/ENOBUFS), which a peer can provoke. */
++ static bool isResourceExhausted(int err);
+ virtual void close(int fd);
+ virtual vector<int> getActiveSockets();
+
+diff --git a/test/AcceptErrorTest.cpp b/test/AcceptErrorTest.cpp
+new file mode 100644
+index 000000000..c52aac933
+--- /dev/null
++++ b/test/AcceptErrorTest.cpp
+@@ -0,0 +1,23 @@
++// Backported from upstream test/unit_tests/UnixSocketHandlerTest.cpp, which
++// 6.2.11 does not have.
++#include "TestHeaders.hpp"
++#include "UnixSocketHandler.hpp"
++
++using namespace et;
++
++TEST_CASE("accept errors a peer can cause do not abort the server",
++ "[AcceptError]") {
++ // Transient, per-connection failures are retried.
++ REQUIRE(UnixSocketHandler::isTransientAcceptError(EAGAIN));
++ REQUIRE(UnixSocketHandler::isTransientAcceptError(EWOULDBLOCK));
++ REQUIRE(UnixSocketHandler::isTransientAcceptError(ECONNABORTED));
++ REQUIRE(UnixSocketHandler::isTransientAcceptError(EINTR));
++ REQUIRE_FALSE(UnixSocketHandler::isTransientAcceptError(EBADF));
++
++ // Exhaustion a peer can provoke is retried too; logic errors are not.
++ REQUIRE(UnixSocketHandler::isResourceExhausted(EMFILE));
++ REQUIRE(UnixSocketHandler::isResourceExhausted(ENFILE));
++ REQUIRE(UnixSocketHandler::isResourceExhausted(ENOMEM));
++ REQUIRE(UnixSocketHandler::isResourceExhausted(ENOBUFS));
++ REQUIRE_FALSE(UnixSocketHandler::isResourceExhausted(EBADF));
++}
+
+From 53a982650d9c65e786dac007a6dc3f4f09d33dc8 Mon Sep 17 00:00:00 2001
+From: Marc Haase <marchaase@gmail.com>
+Date: Wed, 11 Nov 2026 11:18:06 +0000
+Subject: [PATCH 07/12] Disable SO_LINGER: a blocking close() freezes the whole
+ socket layer for 5 seconds (#792)
+
+Every TCP socket etserver accepts gets SO_LINGER {l_onoff=1, l_linger=5} in
+TcpSocketHandler::initSocket. When one is closed with data still unacknowledged,
+close() blocks for the full five seconds.
+
+What makes it bite is where the close happens: UnixSocketHandler::close() takes
+the process-wide globalMutex (line 170), forces the fd blocking at 183 (sockets
+are created non-blocking, and Linux ignores a nonzero linger on a non-blocking
+socket, so that line is what arms it), then calls the blocking ::close() at 190.
+The lock_guard is function-scoped, so the mutex is held until 194.
+
+So it is not one listener stalling: every thread in etserver that touches any
+socket stalls for five seconds because one unrelated connection is tearing down.
+Interactive terminal sessions are among those threads.
+
+Setting l_onoff = 0 disables the linger without removing the setsockopt call.
+
+Measured with a standalone repro containing no ET code (peer accepts and never
+reads, fill the send buffer, set SO_LINGER, close):
+
+ l_onoff=1, l_linger=5 close() 5156 5118 5120 5119 5118 5120 ms (18/18 blocked)
+ no SO_LINGER close() 0 0 0 0 0 0 ms (18/18 instant)
+ l_onoff=0, l_linger=0 close() 0 0 0 0 0 0 ms
+ l_onoff=1, l_linger=2 median 2046.5 ms
+
+Halving l_linger halves the stall (ratio 0.3998 vs a predicted 0.4000), which
+rules out the other two five-second constants in the codebase.
+
+A patched etserver vs stock, 20 trials with alternating arms and an identical
+1,824,768 bytes queued every trial:
+
+ l_onoff=1 (stock) n=10 median 5.1184s max 5.4877s 10/10 blocked
+ l_onoff=0 (patched) n=10 median 0.0000s max 0.0000s 0/10
+
+Note: this will not reproduce on macOS, which drains the receive queue during
+close() even when the peer never reads (~51ms rather than ~5000ms).
+
+Co-authored-by: Marc Haase <marchaase@fb.com>
+(cherry picked from commit 584a68b4b54c74de7035e6108f49151ebce6a191)
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/TcpSocketHandler.cpp | 8 ++++++--
+ 1 file changed, 6 insertions(+), 2 deletions(-)
+
+diff --git a/src/base/TcpSocketHandler.cpp b/src/base/TcpSocketHandler.cpp
+index f4a83a10a..2682e165a 100644
+--- a/src/base/TcpSocketHandler.cpp
++++ b/src/base/TcpSocketHandler.cpp
+@@ -276,9 +276,13 @@ void TcpSocketHandler::initSocket(int fd) {
+ setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int)));
+ }
+ {
+- // Set linger if possible
++ // Linger is disabled deliberately. With l_onoff=1, closing a socket that
++ // still has unacknowledged data blocks in ::close() for the full l_linger
++ // seconds -- and UnixSocketHandler::close() calls it while holding the
++ // process-wide globalMutex, so one connection tearing down freezes every
++ // thread in etserver, terminal sessions included.
+ struct linger so_linger;
+- so_linger.l_onoff = 1;
++ so_linger.l_onoff = 0;
+ so_linger.l_linger = 5;
+ FATAL_FAIL_UNLESS_EINVAL(setsockopt(
+ fd, SOL_SOCKET, SO_LINGER, (const char *)&so_linger, sizeof so_linger));
+
+From ba366343c15b8fb72c9a599c76d863beb6a58633 Mon Sep 17 00:00:00 2001
+From: Bryan O'Sullivan <bos@serpentine.com>
+Date: Wed, 11 Nov 2026 11:18:29 +0000
+Subject: [PATCH 08/12] fix: allocate framed proto bodies only as bytes arrive
+
+A reconnecting peer could advertise a large catchup length, up to the
+128 MiB limit, and send no body, pinning the entire declared allocation in
+the shared daemon until the read timed out.
+
+Read length-prefixed proto bodies in 64 KiB chunks, growing the buffer
+only as data arrives, under one absolute deadline for the whole body.
+Large bodies cost some reallocation. A test reads a body spanning several
+chunks.
+
+(cherry picked from commit 9c69c810bcd66d6f4948a7b667e6285f72ab96c7)
+
+Backport to 6.2.11: the test is a new test/ReadSizedStringTest.cpp with a
+minimal fd-based socket handler.
+
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/SocketHandler.cpp | 30 +++++++++++++++++++++
+ src/base/SocketHandler.hpp | 6 +++--
+ test/ReadSizedStringTest.cpp | 51 ++++++++++++++++++++++++++++++++++++
+ 3 files changed, 85 insertions(+), 2 deletions(-)
+ create mode 100644 test/ReadSizedStringTest.cpp
+
+diff --git a/src/base/SocketHandler.cpp b/src/base/SocketHandler.cpp
+index efcb5e133..b3da68ee3 100644
+--- a/src/base/SocketHandler.cpp
++++ b/src/base/SocketHandler.cpp
+@@ -14,6 +14,36 @@ void SocketHandler::readAll(int fd, void* buf, size_t count, bool timeout) {
+ }
+ }
+
++string SocketHandler::readSizedString(int fd, size_t length, bool timeout) {
++ string result;
++ std::chrono::steady_clock::time_point deadline;
++ if (timeout) {
++ deadline = std::chrono::steady_clock::now() +
++ std::chrono::seconds(SOCKET_ABSOLUTE_TIMEOUT_SEC);
++ }
++ while (result.size() < length) {
++ int remainingSeconds = 0;
++ if (timeout) {
++ const auto remaining = deadline - std::chrono::steady_clock::now();
++ if (remaining <= std::chrono::steady_clock::duration::zero()) {
++ throw std::runtime_error("Socket Timeout");
++ }
++ remainingSeconds =
++ static_cast<int>(
++ std::chrono::duration_cast<std::chrono::seconds>(remaining)
++ .count()) +
++ 1;
++ }
++ const size_t offset = result.size();
++ const size_t count = std::min<size_t>(64 * 1024, length - offset);
++ // Grow only as bytes arrive; never reserve the declared length.
++ result.resize(offset + count);
++ readAll(fd, result.data() + offset, count,
++ timeout ? SOCKET_IDLE_TIMEOUT_SEC : 0, remainingSeconds);
++ }
++ return result;
++}
++
+ void SocketHandler::readAll(int fd, void* buf, size_t count, int idleTimeoutSec,
+ int absoluteTimeoutSec) {
+ time_t absoluteStartTime = time(NULL);
+diff --git a/src/base/SocketHandler.hpp b/src/base/SocketHandler.hpp
+index fb1a5674c..c7f631764 100644
+--- a/src/base/SocketHandler.hpp
++++ b/src/base/SocketHandler.hpp
+@@ -34,6 +34,9 @@ class SocketHandler {
+ */
+ void readAll(int fd, void* buf, size_t count, int idleTimeoutSec,
+ int absoluteTimeoutSec);
++ /** @brief Reads a framed body incrementally, allocating only as bytes
++ * arrive, with one absolute deadline for the entire body. */
++ string readSizedString(int fd, size_t length, bool timeout);
+ /**
+ * @brief Attempts to write the full buffer and returns -1 on timeout/failure.
+ * @return Total bytes written or -1 when the socket deadlocks.
+@@ -79,8 +82,7 @@ class SocketHandler {
+ if (length == 0) {
+ return t;
+ }
+- string s(length, '\0');
+- readAll(fd, &s[0], length, timeout);
++ string s = readSizedString(fd, static_cast<size_t>(length), timeout);
+ if (!t.ParseFromString(s)) {
+ throw std::runtime_error("Invalid proto");
+ }
+diff --git a/test/ReadSizedStringTest.cpp b/test/ReadSizedStringTest.cpp
+new file mode 100644
+index 000000000..8e52c1ac6
+--- /dev/null
++++ b/test/ReadSizedStringTest.cpp
+@@ -0,0 +1,51 @@
++// Backported from upstream test/unit_tests/BackedIOTest.cpp, which 6.2.11
++// does not have.
++#include <sys/socket.h>
++#include <unistd.h>
++
++#include <thread>
++
++#include "ETerminal.pb.h"
++#include "SocketHandler.hpp"
++#include "TestHeaders.hpp"
++
++using namespace et;
++
++namespace {
++// Minimal handler that reads and writes plain file descriptors.
++class FdSocketHandler : public SocketHandler {
++ public:
++ bool hasData(int fd) override { return waitOnSocketData(fd); }
++ ssize_t read(int fd, void* buf, size_t count) override {
++ return ::read(fd, buf, count);
++ }
++ ssize_t write(int fd, const void* buf, size_t count) override {
++ return ::write(fd, buf, count);
++ }
++ int connect(const SocketEndpoint&) override { return -1; }
++ set<int> listen(const SocketEndpoint&) override { return {}; }
++ set<int> getEndpointFds(const SocketEndpoint&) override { return {}; }
++ int accept(int fd) override { return fd; }
++ void stopListening(const SocketEndpoint&) override {}
++ void close(int fd) override { ::close(fd); }
++ vector<int> getActiveSockets() override { return {}; }
++};
++} // namespace
++
++TEST_CASE("SocketHandler readProto reassembles bodies across read chunks",
++ "[SocketHandler]") {
++ FdSocketHandler handler;
++ int fds[2];
++ REQUIRE(::socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
++
++ et::CatchupBuffer sent;
++ sent.add_buffer(string(200 * 1024, 'x'));
++ std::thread writer([&]() { handler.writeProto(fds[1], sent, true); });
++ const auto received = handler.readProto<et::CatchupBuffer>(fds[0], true);
++ writer.join();
++ REQUIRE(received.buffer_size() == 1);
++ REQUIRE(received.buffer(0) == sent.buffer(0));
++
++ handler.close(fds[0]);
++ handler.close(fds[1]);
++}
+
+From 22f64439b7429c13ac91dfe8cbdadc5b6667e5ef Mon Sep 17 00:00:00 2001
+From: Vasily Zakharov <74466943+vzd3v@users.noreply.github.com>
+Date: Wed, 11 Nov 2026 11:18:57 +0000
+Subject: [PATCH 09/12] Stop a stuck client reconnect from blocking every new
+ connection (#798)
+
+Core of the upstream change, which a remote peer knowing a client id can
+otherwise use to stall etserver:
+
+etserver stops accepting connections entirely while a single client is
+reconnecting over a dead network path. The accept loop and the reconnect
+path contend for the same server-wide lock: a returning client's recovery
+ran under classMutex, and every socket operation in it blocks for up to
+the socket timeout, so nothing can be accepted in the meantime.
+
+Take the recovery out of classMutex. recoverClient() now holds
+connectionMutex across the whole socket swap, so two reconnects for one
+client still cannot interleave, while reconnects for different clients
+stop blocking each other and the accept loop. removeClient() and
+destroyPartialConnection() drop the entry from the maps under classMutex
+and shut the connection down after releasing it. recover() returns early
+when the connection is already shutting down, and a second reconnect for
+a client that already has one in flight is refused rather than queued on
+the shared handler pool.
+
+(cherry picked from commit 50b961d9e9eb6daf57d8a5ce9cae8f9209bffe44)
+
+Backport to 6.2.11: only the locking changes in Connection,
+ServerClientConnection and ServerConnection. Left out: the configurable
+listen backlog, the initial-payload deadline and the freeaddrinfo() leak
+fix, and the tests, which need fixtures 6.2.11 does not have.
+
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/Connection.cpp | 7 ++++
+ src/base/ServerClientConnection.cpp | 52 +++++++++++++++++++++--------
+ src/base/ServerClientConnection.hpp | 10 ++++++
+ src/base/ServerConnection.cpp | 46 ++++++++++++++++---------
+ 4 files changed, 86 insertions(+), 29 deletions(-)
+
+diff --git a/src/base/Connection.cpp b/src/base/Connection.cpp
+index 943342457..440544291 100644
+--- a/src/base/Connection.cpp
++++ b/src/base/Connection.cpp
+@@ -96,6 +96,13 @@ void Connection::closeSocket() {
+ bool Connection::recover(int newSocketFd) {
+ LOG(INFO) << "Locking reader/writer to recover...";
+ lock_guard<std::recursive_mutex> guard(connectionMutex);
++ if (shuttingDown) {
++ // The session was torn down while this reconnect was in flight. Reviving
++ // the reader/writer here would resurrect a dead connection.
++ LOG(INFO) << "Not recovering: connection is shutting down";
++ socketHandler->close(newSocketFd);
++ return false;
++ }
+ lock_guard<std::mutex> readerGuard(reader->getRecoverMutex());
+ lock_guard<std::mutex> writerGuard(writer->getRecoverMutex());
+ LOG(INFO) << "Recovering with socket fd " << newSocketFd << "...";
+diff --git a/src/base/ServerClientConnection.cpp b/src/base/ServerClientConnection.cpp
+index 3005f6491..9c4d420f0 100644
+--- a/src/base/ServerClientConnection.cpp
++++ b/src/base/ServerClientConnection.cpp
+@@ -1,10 +1,22 @@
+ #include "ServerClientConnection.hpp"
+
+ namespace et {
++namespace {
++/** @brief Clears the in-flight flag however recoverClient() returns. */
++class InFlightGuard {
++ public:
++ explicit InFlightGuard(std::atomic<bool>& _flag) : flag(_flag) {}
++ ~InFlightGuard() { flag.store(false); }
++
++ private:
++ std::atomic<bool>& flag;
++};
++} // namespace
++
+ ServerClientConnection::ServerClientConnection(
+ const std::shared_ptr<SocketHandler>& _socketHandler,
+ const string& clientId, int _socketFd, const string& key)
+- : Connection(_socketHandler, clientId, key) {
++ : Connection(_socketHandler, clientId, key), recoveryInFlight(false) {
+ socketFd = _socketFd;
+ reader = shared_ptr<BackedReader>(
+ new BackedReader(socketHandler,
+@@ -25,20 +37,35 @@ ServerClientConnection::~ServerClientConnection() {
+ }
+
+ bool ServerClientConnection::recoverClient(int newSocketFd) {
++ bool idle = false;
++ if (!recoveryInFlight.compare_exchange_strong(idle, true)) {
++ // Waiting for the reconnect that is already running would hold this handler
++ // thread for as long as that one blocks, which against a silent peer is the
++ // full socket timeout. Every other client's handshake runs on the same
++ // small pool, so refusing is cheaper for everyone: a real client is between
++ // attempts of its own reconnect loop and will come back.
++ LOG(INFO) << "Refusing reconnect for " << getId()
++ << ": another one is already in flight";
++ socketHandler->close(newSocketFd);
++ return false;
++ }
++ InFlightGuard inFlightGuard(recoveryInFlight);
++
++ // Held across the whole recovery so two reconnects for the same client cannot
++ // interleave their socket swaps. connectionMutex is recursive, so recover()
++ // re-locking it below is fine.
++ lock_guard<std::recursive_mutex> guard(connectionMutex);
++
+ // Detach the live session without closing it until recover succeeds, so a
+ // failed/malicious reconnect cannot force-disconnect the victim.
+- int oldSocketFd = -1;
+- {
+- lock_guard<std::recursive_mutex> guard(connectionMutex);
+- oldSocketFd = socketFd;
+- if (reader) {
+- reader->invalidateSocket();
+- }
+- if (writer) {
+- writer->invalidateSocket();
+- }
+- socketFd = -1;
++ int oldSocketFd = socketFd;
++ if (reader) {
++ reader->invalidateSocket();
++ }
++ if (writer) {
++ writer->invalidateSocket();
+ }
++ socketFd = -1;
+
+ bool success = recover(newSocketFd);
+ if (success) {
+@@ -49,7 +76,6 @@ bool ServerClientConnection::recoverClient(int newSocketFd) {
+ }
+
+ if (oldSocketFd != -1) {
+- lock_guard<std::recursive_mutex> guard(connectionMutex);
+ socketFd = oldSocketFd;
+ if (reader) {
+ reader->revive(oldSocketFd, vector<string>());
+diff --git a/src/base/ServerClientConnection.hpp b/src/base/ServerClientConnection.hpp
+index 721dd8388..6a2b0b268 100644
+--- a/src/base/ServerClientConnection.hpp
++++ b/src/base/ServerClientConnection.hpp
+@@ -16,12 +16,22 @@ class ServerClientConnection : public Connection {
+ /**
+ * @brief Attempts recovery on the new fd; closes the old socket only after
+ * recover succeeds.
++ *
++ * Returns false without touching the live session if another reconnect for
++ * this client is already in flight.
+ */
+ bool recoverClient(int newSocketFd);
+
+ bool verifyPasskey(const string& targetKey);
+
+ protected:
++ /**
++ * @brief Set while a reconnect is mid-handshake.
++ *
++ * Lets a second reconnect be refused rather than queued, since queueing it
++ * would occupy a handler thread for as long as the first one blocks.
++ */
++ std::atomic<bool> recoveryInFlight;
+ };
+ } // namespace et
+
+diff --git a/src/base/ServerConnection.cpp b/src/base/ServerConnection.cpp
+index 4a0c4841a..5acbb3b51 100644
+--- a/src/base/ServerConnection.cpp
++++ b/src/base/ServerConnection.cpp
+@@ -130,7 +130,11 @@ void ServerConnection::clientHandler(int clientSocketFd) {
+ response.set_status(RETURNING_CLIENT);
+ socketHandler->writeProto(clientSocketFd, response, true);
+
+- lock_guard<std::recursive_mutex> guard(classMutex);
++ // Deliberately not under classMutex: recover() blocks on socket I/O for
++ // as long as the socket timeout allows, and holding a server-wide lock
++ // across that stalls the accept loop until the reconnect gives up.
++ // serverClientState keeps the connection alive, and recoverClient()
++ // serializes concurrent reconnects on the connection's own mutex.
+ serverClientState->recoverClient(clientSocketFd);
+ }
+ } catch (const runtime_error& err) {
+@@ -152,28 +156,38 @@ void ServerConnection::clientHandler(int clientSocketFd) {
+ }
+
+ bool ServerConnection::removeClient(const string& id) {
+- lock_guard<std::recursive_mutex> guard(classMutex);
+- if (clientKeys.find(id) == clientKeys.end()) {
+- return false;
+- }
+- clientKeys.erase(id);
+- if (clientConnections.find(id) == clientConnections.end()) {
+- return true;
++ shared_ptr<ServerClientConnection> connection;
++ {
++ lock_guard<std::recursive_mutex> guard(classMutex);
++ if (clientKeys.find(id) == clientKeys.end()) {
++ return false;
++ }
++ clientKeys.erase(id);
++ const auto it = clientConnections.find(id);
++ if (it == clientConnections.end()) {
++ return true;
++ }
++ connection = it->second;
++ clientConnections.erase(it);
+ }
+- auto connection = clientConnections[id];
++ // Outside classMutex: shutdown() waits on the connection mutex, which a
++ // reconnect can hold across blocking socket I/O.
+ connection->shutdown();
+- clientConnections.erase(id);
+ return true;
+ }
+
+ void ServerConnection::destroyPartialConnection(const string& clientId) {
+- lock_guard<std::recursive_mutex> guard(classMutex);
+- const auto it = clientConnections.find(clientId);
+- if (it == clientConnections.end()) {
+- return;
++ shared_ptr<ServerClientConnection> connection;
++ {
++ lock_guard<std::recursive_mutex> guard(classMutex);
++ const auto it = clientConnections.find(clientId);
++ if (it == clientConnections.end()) {
++ return;
++ }
++ connection = it->second;
++ clientConnections.erase(it);
+ }
+- it->second->shutdown();
+- clientConnections.erase(it);
++ connection->shutdown();
+ }
+
+ } // namespace et
+
+From b61e2d645e595cee11fc6395b1cbd88c50f59b59 Mon Sep 17 00:00:00 2001
+From: Bryan O'Sullivan <bos@serpentine.com>
+Date: Wed, 11 Nov 2026 11:19:33 +0000
+Subject: [PATCH 10/12] fix: authenticate both ends of Unix HTM control
+ connections
+
+A local user could pre-bind another user's predictable HTM socket path.
+The victim client treated the path's existence as daemon readiness, then
+sent keystrokes to the impersonator and displayed its output. The daemon
+also accepted control connections without checking the connecting user.
+
+Check kernel peer credentials on both ends and drop connections from any
+other user before control data flows; the client then exits with an error.
+A squatter can still keep htmd from binding its socket, which is a denial
+of service only. Windows has no AF_UNIX peer credentials, so access there
+still depends on filesystem ACLs.
+
+(cherry picked from commit f8a3b184260cf8d570d524611aa6378e498f1563)
+
+Backport to 6.2.11: 6.2.11 has no PlatformUtils, so GetPeerCredentials
+moves from UserTerminalRouter.cpp into Headers.hpp, shared by the router and
+both IPC ends.
+
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/Headers.hpp | 20 ++++++++++++++++++++
+ src/htm/IpcPairClient.cpp | 11 +++++++++++
+ src/htm/IpcPairServer.cpp | 11 +++++++++++
+ src/terminal/UserTerminalRouter.cpp | 20 --------------------
+ 4 files changed, 42 insertions(+), 20 deletions(-)
+
+diff --git a/src/base/Headers.hpp b/src/base/Headers.hpp
+index 49279c410..f22ebe766 100644
+--- a/src/base/Headers.hpp
++++ b/src/base/Headers.hpp
+@@ -323,6 +323,26 @@ class MalformedPacketError : public std::runtime_error {
+ using std::runtime_error::runtime_error;
+ };
+
++#ifndef WIN32
++// Reads the effective uid and gid of the process at the other end of the
++// connected Unix-domain socket fd, as recorded by the kernel. Returns false if
++// the kernel cannot report them.
++inline bool GetPeerCredentials(int fd, uid_t* uid, gid_t* gid) {
++#ifdef __linux__
++ struct ucred cred;
++ socklen_t len = sizeof(cred);
++ if (::getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) {
++ return false;
++ }
++ *uid = cred.uid;
++ *gid = cred.gid;
++ return true;
++#else
++ return ::getpeereid(fd, uid, gid) == 0;
++#endif
++}
++#endif
++
+ template <typename T>
+ inline T stringToProto(const string& s) {
+ T t;
+diff --git a/src/htm/IpcPairClient.cpp b/src/htm/IpcPairClient.cpp
+index fd07779fa..b41158232 100644
+--- a/src/htm/IpcPairClient.cpp
++++ b/src/htm/IpcPairClient.cpp
+@@ -9,6 +9,17 @@ IpcPairClient::IpcPairClient(shared_ptr<SocketHandler> _socketHandler,
+ if (endpointFd < 0) {
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ } else {
++#ifndef WIN32
++ // Another user can bind the predictable path first; refuse to send
++ // our keystrokes to it.
++ uid_t peerUid;
++ gid_t peerGid;
++ if (!GetPeerCredentials(endpointFd, &peerUid, &peerGid) ||
++ peerUid != ::geteuid()) {
++ closeEndpoint();
++ throw std::runtime_error("HTM IPC server belongs to a different user");
++ }
++#endif
+ return;
+ }
+ }
+diff --git a/src/htm/IpcPairServer.cpp b/src/htm/IpcPairServer.cpp
+index 1e1e74f53..b98ec17d3 100644
+--- a/src/htm/IpcPairServer.cpp
++++ b/src/htm/IpcPairServer.cpp
+@@ -16,6 +16,17 @@ void IpcPairServer::pollAccept() {
+ return;
+ }
+
++#ifndef WIN32
++ // The socket path is predictable; only this user may drive the daemon.
++ uid_t peerUid;
++ gid_t peerGid;
++ if (!GetPeerCredentials(fd, &peerUid, &peerGid) || peerUid != ::geteuid()) {
++ LOG(ERROR) << "Rejecting htm IPC connection from a different user";
++ socketHandler->close(fd);
++ return;
++ }
++#endif
++
+ if (endpointFd >= 0) {
+ // Need to disconnect the current client
+ closeEndpoint();
+diff --git a/src/terminal/UserTerminalRouter.cpp b/src/terminal/UserTerminalRouter.cpp
+index 71d12185a..3bd9b1827 100644
+--- a/src/terminal/UserTerminalRouter.cpp
++++ b/src/terminal/UserTerminalRouter.cpp
+@@ -4,26 +4,6 @@
+ #include "ETerminal.pb.h"
+
+ namespace et {
+-namespace {
+-// Reads the effective uid and gid of the process at the other end of the
+-// connected Unix-domain socket fd, as recorded by the kernel. Returns false if
+-// the kernel cannot report them.
+-bool GetPeerCredentials(int fd, uid_t* uid, gid_t* gid) {
+-#ifdef __linux__
+- struct ucred cred;
+- socklen_t len = sizeof(cred);
+- if (::getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) {
+- return false;
+- }
+- *uid = cred.uid;
+- *gid = cred.gid;
+- return true;
+-#else
+- return ::getpeereid(fd, uid, gid) == 0;
+-#endif
+-}
+-} // namespace
+-
+ UserTerminalRouter::UserTerminalRouter(
+ shared_ptr<PipeSocketHandler> _socketHandler,
+ const SocketEndpoint &_routerEndpoint)
+
+From 78d66126f50185514011a42b74d4b80addba8e17 Mon Sep 17 00:00:00 2001
+From: Eric Psalmond <epsalmond@users.noreply.github.com>
+Date: Wed, 11 Nov 2026 11:45:27 +0000
+Subject: [PATCH 11/12] fix: join the handshake pool outside classMutex on
+ shutdown
+
+Since the pending-handshake cap, each handshake task takes classMutex
+after clientHandler returns to decrement the count. shutdown() held
+classMutex while resetting the pool, which joins the workers, so a
+handshake in flight at shutdown deadlocked etserver until systemd killed
+it. Stop listening under the lock, join the pool without it, then shut
+down the remaining connections under it again, as upstream does.
+
+Refs: 540367ac4509be41714769cf511d8c0aa90cde7a (ServerConnection::shutdown part only)
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/base/ServerConnection.cpp | 8 ++++++--
+ 1 file changed, 6 insertions(+), 2 deletions(-)
+
+diff --git a/src/base/ServerConnection.cpp b/src/base/ServerConnection.cpp
+index 5acbb3b51..7041ddac7 100644
+--- a/src/base/ServerConnection.cpp
++++ b/src/base/ServerConnection.cpp
+@@ -37,9 +37,13 @@ bool ServerConnection::acceptNewConnection(int fd) {
+ }
+
+ void ServerConnection::shutdown() {
+- lock_guard<std::recursive_mutex> guard(classMutex);
+- socketHandler->stopListening(serverEndpoint);
++ {
++ lock_guard<std::recursive_mutex> guard(classMutex);
++ socketHandler->stopListening(serverEndpoint);
++ }
++ // In-flight clientHandlers take classMutex, so join the pool without it.
+ clientHandlerThreadPool.reset();
++ lock_guard<std::recursive_mutex> guard(classMutex);
+ for (const auto& it : clientConnections) {
+ it.second->shutdown();
+ }
+
+From 427fca4d138e75b333e18f328824f892118455dd Mon Sep 17 00:00:00 2001
+From: Bryan O'Sullivan <bos@serpentine.com>
+Date: Wed, 11 Nov 2026 11:47:40 +0000
+Subject: [PATCH 12/12] fix: keep silent router peers from blocking the shared
+ accept loop
+
+Any local user could connect to the world-connectable router socket and
+withhold registration data. The shared accept loop blocked on that read
+for as long as the peer stayed connected, halting all new connections.
+
+Read registrations without blocking: each must fit in 4 KiB and finish
+within 30 seconds, with at most 64 pending. The loop advances pending
+registrations on every tick and polls their sockets, refreshing the poller
+when descriptors are reused, so fragmented packets wake it at once. Bytes
+after the registration packet stay with the session. A local user holding
+64 silent connections can still delay new registrations, but no longer
+blocks TCP clients. Tests cover a silent peer alongside a valid one,
+expiry, fragmented-read wakeups, and the data following a registration.
+
+(cherry picked from commit f37750d54c85160dfe0a2266719f03c31448532f)
+
+Backport to 6.2.11: 6.2.11 has no FdPoller, so TerminalServer::run adds the
+pending registration descriptors to its select() set each tick (skipping any
+at or above FD_SETSIZE, which are still advanced every tick) and calls
+acceptNewConnection() on every iteration so pending reads advance and time
+out. This also removes the router accept path that aborted the daemon on
+accept errors the earlier backports now report instead of aborting on.
+routerMutex becomes mutable for the const pendingRegistrationFds(). The
+7.x-only router functions in the same hunk are left out; tests ported into
+test/UserTerminalRouterTest.cpp without the FdPoller check.
+
+Assisted-by: Claude Code:claude-opus-5-5
+Signed-off-by: Michel Lind <salimma@fedoraproject.org>
+---
+ src/terminal/TerminalServer.cpp | 24 ++++++--
+ src/terminal/UserTerminalRouter.cpp | 94 ++++++++++++++++++++++++-----
+ src/terminal/UserTerminalRouter.hpp | 20 +++++-
+ test/UserTerminalRouterTest.cpp | 84 ++++++++++++++++++++++++++
+ 4 files changed, 202 insertions(+), 20 deletions(-)
+
+diff --git a/src/terminal/TerminalServer.cpp b/src/terminal/TerminalServer.cpp
+index 44a22c648..022bfe73e 100644
+--- a/src/terminal/TerminalServer.cpp
++++ b/src/terminal/TerminalServer.cpp
+@@ -40,6 +40,8 @@ void TerminalServer::run() {
+ __FILE__, __LINE__);
+ }
+
++ uint64_t pendingFdsGeneration = 0;
++ set<int> pendingRouterFds;
+ while (true) {
+ {
+ lock_guard<std::mutex> guard(terminalThreadMutex);
+@@ -51,6 +53,20 @@ void TerminalServer::run() {
+ fd_set rfds = coreFds;
+ int numFds = numCoreFds;
+ int maxFd = maxCoreFd;
++ if (const auto pending =
++ terminalRouter->pendingRegistrationFds(pendingFdsGeneration)) {
++ pendingRouterFds = *pending;
++ }
++ for (int fd : pendingRouterFds) {
++ if (fd >= FD_SETSIZE) {
++ // Still advanced each tick by acceptNewConnection(); just not
++ // watched, since fd_set cannot hold it.
++ continue;
++ }
++ FD_SET(fd, &rfds);
++ maxFd = max(maxFd, fd);
++ numFds++;
++ }
+ timeval tv;
+
+ if (numFds > FD_SETSIZE) {
+@@ -69,17 +85,15 @@ void TerminalServer::run() {
+ }
+
+ FATAL_FAIL(numFdsSet);
+- if (numFdsSet == 0) {
+- continue;
+- }
+
+- // We have something to do!
+ for (int i : serverPortFds) {
+ if (FD_ISSET(i, &rfds)) {
+ acceptNewConnection(i);
+ }
+ }
+- if (FD_ISSET(terminalRouter->getServerFd(), &rfds)) {
++ {
++ // Pending registrations advance (and time out) even when the listener
++ // has no new peers.
+ auto idKeyPair = terminalRouter->acceptNewConnection();
+ if (idKeyPair.id.length()) {
+ addClientKey(idKeyPair.id, idKeyPair.key);
+diff --git a/src/terminal/UserTerminalRouter.cpp b/src/terminal/UserTerminalRouter.cpp
+index 3bd9b1827..30110129e 100644
+--- a/src/terminal/UserTerminalRouter.cpp
++++ b/src/terminal/UserTerminalRouter.cpp
+@@ -15,27 +15,93 @@ UserTerminalRouter::UserTerminalRouter(
+ S_IROTH | S_IWOTH | S_IXOTH));
+ }
+
++std::optional<set<int>> UserTerminalRouter::pendingRegistrationFds(
++ uint64_t& generation) const {
++ lock_guard<recursive_mutex> guard(routerMutex);
++ if (generation == pendingFdsGeneration) {
++ return std::nullopt;
++ }
++ generation = pendingFdsGeneration;
++ set<int> fds;
++ for (const auto& entry : pendingRegistrations) {
++ fds.insert(entry.first);
++ }
++ return fds;
++}
++
+ IdKeyPair UserTerminalRouter::acceptNewConnection() {
+ lock_guard<recursive_mutex> guard(routerMutex);
+- LOG(INFO) << "Listening to id/key FIFO";
+- const int terminalFd = socketHandler->accept(serverFd);
+- if (terminalFd < 0) {
+- if (GetErrno() != EAGAIN && GetErrno() != EWOULDBLOCK) {
+- FATAL_FAIL(-1); // STFATAL with the error
++ const int accepted = socketHandler->accept(serverFd);
++ if (accepted >= 0) {
++ if (pendingRegistrations.size() >= MAX_PENDING_REGISTRATIONS) {
++ LOG(WARNING) << "Too many pending router registrations; refusing";
++ socketHandler->close(accepted);
+ } else {
+- return IdKeyPair({"", ""}); // Nothing to accept this time
++ pendingRegistrations.emplace(accepted, PendingRegistration{});
++ ++pendingFdsGeneration;
+ }
+ }
++ for (auto it = pendingRegistrations.begin();
++ it != pendingRegistrations.end();) {
++ const int fd = it->first;
++ auto& pending = it->second;
++ bool failed = std::chrono::steady_clock::now() - pending.started >=
++ REGISTRATION_TIMEOUT;
++ while (!failed && socketHandler->hasData(fd)) {
++ const size_t target =
++ pending.length < 0
++ ? sizeof(int64_t)
++ : sizeof(int64_t) + static_cast<size_t>(pending.length);
++ char buffer[MAX_REGISTRATION_LENGTH];
++ const auto n =
++ socketHandler->read(fd, buffer, target - pending.bytes.size());
++ const int error = GetErrno();
++ if (n < 0 &&
++ (error == EAGAIN || error == EWOULDBLOCK || error == EINTR)) {
++ break;
++ }
++ if (n <= 0) {
++ failed = true;
++ break;
++ }
++ pending.bytes.append(buffer, static_cast<size_t>(n));
++ if (pending.length < 0 && pending.bytes.size() == sizeof(int64_t)) {
++ memcpy(&pending.length, pending.bytes.data(), sizeof(int64_t));
++ if (pending.length < Packet::HEADER_SIZE ||
++ pending.length > MAX_REGISTRATION_LENGTH) {
++ failed = true;
++ break;
++ }
++ }
++ if (pending.length >= 0 &&
++ pending.bytes.size() ==
++ sizeof(int64_t) + static_cast<size_t>(pending.length)) {
++ Packet packet(pending.bytes.substr(sizeof(int64_t)));
++ it = pendingRegistrations.erase(it);
++ ++pendingFdsGeneration;
++ auto result = registerTerminal(fd, packet);
++ if (!result.id.empty()) {
++ return result;
++ }
++ // registerTerminal closed the rejected fd.
++ failed = false;
++ break;
++ }
++ }
++ if (failed) {
++ socketHandler->close(fd);
++ it = pendingRegistrations.erase(it);
++ ++pendingFdsGeneration;
++ } else if (it != pendingRegistrations.end() && it->first == fd) {
++ ++it;
++ }
++ }
++ return IdKeyPair({"", ""});
++}
+
+- LOG(INFO) << "Connected";
+-
++IdKeyPair UserTerminalRouter::registerTerminal(int terminalFd,
++ const Packet& packet) {
+ try {
+- Packet packet;
+- if (!socketHandler->readPacket(terminalFd, &packet)) {
+- LOG(ERROR) << "Empty router registration packet";
+- socketHandler->close(terminalFd);
+- return IdKeyPair({"", ""});
+- }
+ if (packet.getHeader() != TerminalPacketType::TERMINAL_USER_INFO) {
+ LOG(ERROR) << "Got an invalid packet header from router peer: "
+ << int(packet.getHeader());
+diff --git a/src/terminal/UserTerminalRouter.hpp b/src/terminal/UserTerminalRouter.hpp
+index 52c4e10b2..3a37a5ea2 100644
+--- a/src/terminal/UserTerminalRouter.hpp
++++ b/src/terminal/UserTerminalRouter.hpp
+@@ -1,6 +1,7 @@
+ #ifndef __ET_USER_TERMINAL_ROUTER__
+ #define __ET_USER_TERMINAL_ROUTER__
+
++#include <chrono>
+ #include <optional>
+
+ #include "Headers.hpp"
+@@ -14,7 +15,12 @@ class UserTerminalRouter {
+ UserTerminalRouter(shared_ptr<PipeSocketHandler> _socketHandler,
+ const SocketEndpoint& _routerEndpoint);
+ inline int getServerFd() { return serverFd; }
++ /** @brief Advances bounded, nonblocking registration reads. Call each tick;
++ * returns one completed registration or an empty pair. */
+ IdKeyPair acceptNewConnection();
++ /** @brief Returns the pending read set after a change, updating generation.
++ * Refresh these descriptors in the poller even if numbers were reused. */
++ std::optional<set<int>> pendingRegistrationFds(uint64_t& generation) const;
+
+ std::optional<TerminalUserInfo> tryGetInfoForConnection(
+ const shared_ptr<ServerClientConnection>& serverClientState);
+@@ -24,10 +30,22 @@ class UserTerminalRouter {
+ }
+
+ protected:
++ struct PendingRegistration {
++ string bytes;
++ int64_t length = -1;
++ std::chrono::steady_clock::time_point started =
++ std::chrono::steady_clock::now();
++ };
++ static constexpr size_t MAX_PENDING_REGISTRATIONS = 64;
++ static constexpr int64_t MAX_REGISTRATION_LENGTH = 4096;
++ static constexpr std::chrono::seconds REGISTRATION_TIMEOUT{30};
++ unordered_map<int, PendingRegistration> pendingRegistrations;
++ uint64_t pendingFdsGeneration = 0;
++ IdKeyPair registerTerminal(int terminalFd, const Packet& packet);
+ int serverFd;
+ unordered_map<string, TerminalUserInfo> idInfoMap;
+ shared_ptr<PipeSocketHandler> socketHandler;
+- recursive_mutex routerMutex;
++ mutable recursive_mutex routerMutex;
+ };
+ } // namespace et
+
+diff --git a/test/UserTerminalRouterTest.cpp b/test/UserTerminalRouterTest.cpp
+index 9d5ab7bda..2e3009ef2 100644
+--- a/test/UserTerminalRouterTest.cpp
++++ b/test/UserTerminalRouterTest.cpp
+@@ -1,4 +1,6 @@
+ #ifndef WIN32
++#include <chrono>
++
+ #include "ETerminal.pb.h"
+ #include "PipeSocketHandler.hpp"
+ #include "TestHeaders.hpp"
+@@ -34,6 +36,18 @@ class InspectableUserTerminalRouter : public UserTerminalRouter {
+ lock_guard<recursive_mutex> guard(routerMutex);
+ return {idInfoMap.at(id).uid(), idInfoMap.at(id).gid()};
+ }
++
++ int terminalFd(const string& id) {
++ lock_guard<recursive_mutex> guard(routerMutex);
++ return idInfoMap.at(id).fd();
++ }
++
++ void expirePending() {
++ for (auto& entry : pendingRegistrations) {
++ entry.second.started -= REGISTRATION_TIMEOUT;
++ }
++ }
++ size_t pendingCount() const { return pendingRegistrations.size(); }
+ };
+
+ // Registers a fake terminal with the given credentials and returns its fd.
+@@ -165,4 +179,74 @@ TEST_CASE("UserTerminalRouter rejects registrations with invalid credentials",
+ socketHandler->close(fdOk);
+ testEndpoint.cleanup(socketHandler);
+ }
++TEST_CASE("UserTerminalRouter reclaims silent registrations",
++ "[UserTerminalRouter]") {
++ // A connection that never sends its registration packet previously
++ // blocked acceptNewConnection forever on the single accept-loop thread.
++ // Incomplete registrations must leave that loop free to serve other peers.
++ auto socketHandler = std::make_shared<PipeSocketHandler>();
++
++ RouterEndpoint testEndpoint;
++ SocketEndpoint routerEndpoint;
++ routerEndpoint.set_name(testEndpoint.path);
++ InspectableUserTerminalRouter router(socketHandler, routerEndpoint);
++
++ int fdSilent = socketHandler->connect(routerEndpoint);
++ REQUIRE(fdSilent >= 0);
++
++ const auto start = std::chrono::steady_clock::now();
++ REQUIRE(router.acceptNewConnection().id.empty());
++ REQUIRE(std::chrono::steady_clock::now() - start < std::chrono::seconds(1));
++ IdKeyPair accepted;
++ const int good =
++ registerFakeTerminal(socketHandler, router, routerEndpoint,
++ "alongside-silent", string(32, 'g'), &accepted);
++ REQUIRE(accepted.id == "alongside-silent");
++ REQUIRE(router.pendingCount() == 1);
++ router.expirePending();
++ REQUIRE(router.acceptNewConnection().id.empty());
++ REQUIRE(router.pendingCount() == 0);
++ socketHandler->close(fdSilent);
++ socketHandler->close(good);
++
++ // A registration may arrive in arbitrary fragments. Its last fragment
++ // may share a socket read with terminal data, which belongs to the session.
++ const int fragmented = socketHandler->connect(routerEndpoint);
++ REQUIRE(fragmented >= 0);
++ TerminalUserInfo tui;
++ tui.set_id("fragmented");
++ tui.set_passkey(string(32, 'k'));
++ const string body =
++ Packet(TerminalPacketType::TERMINAL_USER_INFO, protoToString(tui))
++ .serialize();
++ const int64_t length = body.size();
++ socketHandler->writeAllOrThrow(fragmented, &length, 3, false);
++ REQUIRE(router.acceptNewConnection().id.empty());
++ uint64_t generation = 0;
++ const auto pending = router.pendingRegistrationFds(generation);
++ REQUIRE(pending.has_value());
++ REQUIRE(pending->size() == 1);
++ socketHandler->writeAllOrThrow(fragmented,
++ reinterpret_cast<const char*>(&length) + 3,
++ sizeof(length) - 3, false);
++ socketHandler->writeAllOrThrow(fragmented, body.data(), 1, false);
++ REQUIRE(router.acceptNewConnection().id.empty());
++ socketHandler->writeAllOrThrow(fragmented, body.data() + 1, body.size() - 1,
++ false);
++ socketHandler->writePacket(
++ fragmented,
++ Packet(TerminalPacketType::TERMINAL_BUFFER, "following terminal data"));
++ REQUIRE(router.acceptNewConnection().id == "fragmented");
++ const auto completed = router.pendingRegistrationFds(generation);
++ REQUIRE(completed.has_value());
++ REQUIRE(completed->empty());
++ Packet following;
++ REQUIRE(
++ socketHandler->readPacket(router.terminalFd("fragmented"), &following));
++ REQUIRE(following.getHeader() == TerminalPacketType::TERMINAL_BUFFER);
++ REQUIRE(following.getPayload() == "following terminal data");
++ socketHandler->close(fragmented);
++
++ testEndpoint.cleanup(socketHandler);
++}
+ #endif
diff --git a/et.spec b/et.spec
index c452f40..c22666c 100644
--- a/et.spec
+++ b/et.spec
@@ -23,11 +23,22 @@ Version: 6.2.11
Release: %autorelease
Summary: Remote shell that survives IP roaming and disconnect
-License: Apache-2.0
+# Apache-2.0: et, UniversalStacktrace
+# MIT: base64, PlatformFolders
+# Zlib: sole, ThreadPool
+License: Apache-2.0 AND MIT AND Zlib
URL: https://mistertea.github.io/EternalTerminal/
Source0: https://github.com/MisterTea/EternalTerminal/archive/et-v%{version}/EternalTerminal-%{version}.tar.gz
Source1: et.xml
Patch0: et-use-system-dependency.patch
+# Security fixes from 7.1.x backported to 6.2.11 (pre-auth denial of
+# service, daemon aborts on malformed input, root operations on
+# client-chosen Unix socket paths), as a git format-patch series with one
+# commit per upstream fix, each naming its upstream commit. Proposed for a
+# 6.2 branch upstream in
+# https://github.com/MisterTea/EternalTerminal/issues/923
+# https://github.com/michel-slm/EternalTerminal/tree/backport/6.2.11-security-fixes
+Patch1: et-6.2.11-security-backports.patch
ExcludeArch: %{ix86}
@@ -48,7 +59,6 @@ BuildRequires: json-devel
BuildRequires: json-static
BuildRequires: simpleini-devel
BuildRequires: libatomic
-BuildRequires: libcurl-devel
BuildRequires: libsodium-devel
%if %{with unwind}
BuildRequires: libunwind-devel
@@ -62,26 +72,24 @@ BuildRequires: libselinux-devel
BuildRequires: systemd
# Bundled libraries
-# cat .gitmodules | grep submodule | sort
-# for tarball, s/external/external_imported
-Provides: bundled(base64) = 0
-# external_imported/cotire/CMake/cotire.cmake
-Provides: bundled(cotire) = 1.8.0
-# external/msgpack-c/include/msgpack/version_master.h
-Provides: bundled(msgpack) = 3.3.0
-# external/PlatformFolders/CMakeLists.txt
-Provides: bundled(PlatformFolders) = 4.0.0
-# sanitizers-cmake is only used when building
-%ifnarch ppc64le s390x
-# external/sentry-native/include/sentry.h
-Provides: bundled(sentry-native) = 0.6.0
-%endif
+# Versions are those of the submodule commits pinned at the release tag
+# (external/ in the upstream git repository). The tarball carries them
+# in external_imported/; the prep section checks that only the
+# directories listed here remain, so a newly bundled library fails the
+# build.
+# https://github.com/tkislan/base64
+Provides: bundled(base64) = 0^20200731git6780d5b
+# https://github.com/sago007/PlatformFolders
+Provides: bundled(PlatformFolders) = 4.2.0
# https://github.com/r-lyeh-archived/sole
-Provides: bundled(sole) = 1.0.1
-Provides: bundled(ThreadPool) = 0
-# external/UniversalStacktrace/CMakeLists.txt
-Provides: bundled(UniversalStacktrace) = 0.0.1
-# vcpkg is disabled
+Provides: bundled(sole) = 1.0.1^20200819git424b969
+# https://github.com/progschj/ThreadPool
+Provides: bundled(ThreadPool) = 0^20140926git9a42ec1
+# https://github.com/MisterTea/UniversalStacktrace
+Provides: bundled(UniversalStacktrace) = 0^20210122gite6ca245
+# Not shipped: sanitizers-cmake (build only); easyloggingpp uses the
+# system copy. Removed in prep: Catch2, cotire, cpp-httplib, cxxopts,
+# json, msgpack-c, sentry-native, simpleini, vcpkg
%{?systemd_requires}
@@ -119,11 +127,28 @@ rm -rf external_imported/json
# Unbundle simpleini
rm -rf external_imported/simpleini
+# Unused: cotire, msgpack-c, vcpkg; sentry-native (telemetry disabled)
+for d in cotire msgpack-c sentry-native vcpkg; do
+ rm -r external_imported/$d
+done
+
+# Fail if upstream bundles something new; update the bundled() Provides
+# and License when this list changes
+expected="base64 easyloggingpp PlatformFolders sanitizers-cmake sole ThreadPool UniversalStacktrace"
+actual=$(ls external_imported | LC_ALL=C sort -f | xargs)
+if [ "$actual" != "$expected" ]; then
+ echo "external_imported changed: expected '$expected', got '$actual'" >&2
+ exit 1
+fi
+
+# Telemetry is compiled out (DISABLE_TELEMETRY); do not suggest otherwise
+sed -i 's/^telemetry = true$/telemetry = false/' etc/et.cfg
+
%build
+# DISABLE_TELEMETRY also disables sentry: no crash reports to Sentry or
+# logs to Datadog (and no fixed paths in /tmp, CVE-2023-23558)
%cmake \
-%ifarch ppc64le s390x
- -DDISABLE_SENTRY=ON \
-%endif
+ -DDISABLE_TELEMETRY=ON \
-DDISABLE_VCPKG=ON
%cmake_build
@@ -138,8 +163,6 @@ install -m 0644 -p systemctl/et.service %{buildroot}%{_unitdir}/et.service
install -m 0644 -p etc/et.cfg %{buildroot}%{_sysconfdir}/et.cfg
install -m 0644 %{SOURCE1} %{buildroot}%{_firewalld_dir}/services/et.xml
-rm -vf %{buildroot}%{_bindir}/crashpad_handler
-rm -rf %{buildroot}%{_libdir}/cmake/sentry
rm -vf %{buildroot}%{_libdir}/*.a
%if %{with tests}
reply other threads:[~2026-11-11 21:10 UTC|newest]
Thread overview: [no followups] expand[flat|nested] mbox.gz Atom feed
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=179443143818.1.15225279562933160192.rpms-et-9ebc65f49583@fedoraproject.org \
--to=salimma@fedoraproject.org \
--cc=git-commits@fedoraproject.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox