Skip to content

Fix four pre-auth and privilege-escalation issues from security notices. - #784

Merged
MisterTea merged 4 commits into
masterfrom
jgauci/security_fixes
Jul 30, 2026
Merged

MisterTea merged 4 commits into
masterfrom
jgauci/security_fixes

Conversation

@MisterTea

@MisterTea MisterTea commented Jul 29, 2026 •

Copy link
Copy Markdown
Owner

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.

This issue was found by Anthropic from using agents to study security of open source projects. Ada Logics helped validate the found issues and create the report manually and notify the maintainers.

jasongauci-webai and others added 2 commits July 29, 2026 16:57
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 <[email protected]>
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 <[email protected]>
@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.01657% with 94 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.11%. Comparing base (90711ad) to head (329a911).

Files with missing lines Patch % Lines
test/unit_tests/SecurityNoticesTest.cpp 79.03% 61 Missing ⚠️
src/base/UserSocketOps.cpp 80.26% 30 Missing ⚠️
src/terminal/forwarding/PortForwardHandler.cpp 93.75% 1 Missing ⚠️
test/unit_tests/UnixSocketHandlerTest.cpp 97.14% 1 Missing ⚠️
test/unit_tests/UserSocketOpsTest.cpp 98.97% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #784      +/-   ##
==========================================
+ Coverage   86.99%   87.11%   +0.11%     
==========================================
  Files          72       75       +3     
  Lines        5676     6378     +702     
  Branches      532      601      +69     
==========================================
+ Hits         4938     5556     +618     
- Misses        738      822      +84     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

jasongauci-webai and others added 2 commits July 29, 2026 20:22
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 <[email protected]>
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 <[email protected]>
@MisterTea
MisterTea merged commit 69b3353 into master Jul 30, 2026
32 checks passed
vzd3v added a commit to vzd3v/EternalTerminal that referenced this pull request Aug 28, 2026
Taking the recovery out of classMutex frees the accept loop, but the recovery
still occupies the handler thread it runs on, and reconnects for one client
serialize on that connection's mutex. Overlapping attempts therefore each park a
worker for the length of every attempt ahead of them, and that pool is eight
threads wide and shared with every other client's handshake.

Measured against a real etserver: one live session, four silent reconnects
arriving every fifteen seconds for two minutes, and a fresh client attempting to
connect five times through that window.

    unpatched     hung 45s  hung 45s  13s  0s  0s
    accept fix    0s        0s        42s  1s  13s
    this commit   0s        0s        0s   0s  1s

A real client cannot overlap its own attempts, because pollReconnect() blocks in
its own half of the same handshake before it retries. An unauthenticated peer
can: a reconnect needs nothing but a client id, as MisterTea#784 describes, so a handful
of sockets that answer nothing is enough to hold the pool.

Refusing costs nothing that waiting was buying. The refused socket is closed
before the live session is touched, so the victim keeps its own connection, and a
client that really is reconnecting comes back on its next attempt.

Testing:

A second case in AcceptStarvationTest wedges a recovery, then requires a second
reconnect for the same client to return within five seconds. Without this commit
it waits for the first one's socket timeout and the case fails on that deadline.
It also checks the refused peer sees RETURNING_CLIENT and then EOF, and that the
live session is still registered afterwards. The shared setup the two cases need
moved into a helper.

macOS: 162/162.
MisterTea pushed a commit that referenced this pull request Sep 1, 2026
* Stop a stuck reconnect from blocking every new connection

etserver stops accepting connections entirely while a single client is
reconnecting over a dead network path. `et host` hangs with no matching
server-side log line, the kernel accept queue fills, and service only comes
back when the stuck clients are killed. Seen on 7.0.0 with four abandoned
clients on one laptop: the listening socket sat with 27 connections queued
against a backlog of 32, all from the same source address, while the server
log went quiet.

The accept loop and the reconnect path contend for the same server-wide lock.
TerminalServer::run() calls acceptNewConnection() on its own thread, and that
takes classMutex to enqueue the new descriptor. A returning client is handled
on a pool thread, which took the same lock around the recovery:

    lock_guard<std::recursive_mutex> guard(classMutex);
    serverClientState->recoverClient(clientSocketFd);

recoverClient() calls Connection::recover(), which writes a SequenceHeader,
reads the client's reply, exchanges catchup buffers, and only then returns.
Every one of those four socket operations blocks: reads are bounded by a 30s
idle and 60s absolute deadline, writes by 30s, so a single recovery against a
client that is no longer there can hold classMutex for minutes. Nothing can be
accepted in the meantime, and neither can the router connection that registers
a new session's key, because run() handles both on the same thread.
ClientConnection::pollReconnect() retries once a second and only gives up on
INVALID_KEY, so a few abandoned clients keep the eight-thread pool busy and the
accept queue permanently full.

Take the recovery out of classMutex. The lock was doing two jobs: keeping the
connection alive for the duration of the call, and serializing concurrent
reconnects for the same client. The first is already covered, since
serverClientState is a shared_ptr copy taken under the lock. The second moves
to the connection's own mutex: recoverClient() now holds connectionMutex across
the whole socket swap rather than just the first half, so two reconnects for
one client still cannot interleave, while reconnects for different clients stop
blocking each other and the accept loop. connectionMutex is recursive, so
recover() re-locking it is fine.

removeClient() and destroyPartialConnection() had the mirror-image problem.
They called Connection::shutdown() while holding classMutex, and shutdown()
waits on connectionMutex, which a reconnect can hold across that same blocking
I/O. Both now drop the entry from the maps under classMutex and shut the
connection down after releasing it.

Finally, recover() returns early when the connection is already shutting down.
With the global lock gone, a session can be torn down while a reconnect for it
is in flight, and without the check recover() would revive the reader and
writer of a connection that nobody owns any more.

Testing:

Adds test/unit_tests/AcceptStarvationTest.cpp. It registers a client, opens a
second connection for the same client whose peer never answers the sequence
header -- leaving recover() blocked exactly where a dead path leaves it -- and
then requires acceptNewConnection() to complete for an unrelated descriptor.
Pre-fix the accept is still blocked when the five second deadline expires;
post-fix it returns in under a millisecond. Teardown unblocks the stuck worker,
so a regression fails in five seconds instead of hanging the suite.

ctest is green, including the existing recoverClient coverage in
SecurityNoticesTest, and the ServerConnection tests report no races under
ThreadSanitizer.

* Make the listen backlog configurable

TcpSocketHandler::listen() hardcoded a backlog of 32. That queue is what the
accept loop drains, so it bounds how many clients can be mid-connect at once;
once it is full the kernel stops completing handshakes and `et host` hangs with
nothing written to the server log. Thirty-two is small for a daemon whose
clients tend to reconnect all at once, after a network partition or when a
laptop wakes up, and there was no way to raise it short of rebuilding.

Default to 128 and allow an override through `backlog` in the [Networking]
section of et.cfg. Non-positive values fall back to the default instead of
being handed to listen(), where their meaning is implementation defined.

A deeper queue does not fix an accept loop that has stopped draining it, it
only buys time. It does stop an ordinary reconnect burst from reaching the
cliff in the first place.

Testing:

Adds test/unit_tests/TcpSocketHandlerTest.cpp covering the default, an explicit
value, the non-positive fallback, and a real listen() with a non-default
backlog on a loopback ephemeral port.

* Bound the wait for a client's initial payload

TerminalServer::handleConnection() waited forever for the first packet:

    while (!serverClientState->readPacket(&packet)) {
      LOG(INFO) << "Waiting for initial packet...";
      sleep(1);
    }

A client that finishes the handshake and then goes away leaves that thread
spinning for the life of the process, emitting a line of log every second. On
a server hit by a reconnect storm one such thread had been looping for over
forty minutes, and its messages dominated the log.

The loop also has no exit for shutdown. readPacket() returns false once the
connection is shutting down, so the thread keeps looping while run() blocks
joining it and etserver never exits cleanly.

Give up when the connection is shutting down, or after ten minutes. Little is
lost either way: the initial payload is what starts the terminal, so a client
that never sends one has no session to preserve, and a client whose path
recovers before the deadline still reaches the same thread through the normal
reconnect. Cleanup matches the end of runTerminal(). The surviving log line is
throttled to one in ten.

Testing:

Adds test/integration_tests/HandleConnectionTimeoutTest.cpp, which calls
handleConnection() with an already shut down connection and requires it to
return. Pre-fix it never does. The worker is detached on failure so a
regression is reported instead of hanging the suite.

* Exit the initial-payload wait when the server is halted

The wait added in the previous commit checked the connection's own shutdown
flag, but that flag is not what stops this server. TerminalServer::shutdown()
only sets `halt`, and the unqualified shutdown() in run() resolves to it rather
than ServerConnection::shutdown(), so nothing ever marks these connections as
shutting down. A client that connected without sending an initial payload
therefore kept its thread looping, and run() blocked joining it for up to the
ten minute deadline.

Check `halt` under terminalThreadMutex, the way the session loops in
runJumpHost() and runTerminal() already do, so the thread leaves within a
second of shutdown. The flag is read into a local and the lock released before
removeClient() takes classMutex, so the existing classMutex ->
terminalThreadMutex order stays the only one in play.

Testing:

Adds a second case to HandleConnectionTimeoutTest for a client whose socket is
open and silent -- the state that used to loop forever -- requiring
handleConnection() to return once the server is halted. It fails on the parent
commit and passes here.

That case needs a connection the server does not own: UnixSocketHandler refuses
descriptors it did not create, so a socketpair is passed through a raw
descriptor handler, and set non-blocking as initSocket() leaves every real
socket. A blocking descriptor parks BackedReader::read() while it holds the
connection mutex, which is also why teardown only shuts the connection down on
the passing path.

* Free the address info in TcpSocketHandler::listen()

listen() has never called freeaddrinfo() on the servinfo it obtains at
TcpSocketHandler.cpp:175, neither on its normal return nor on the bind failure
that throws. connect() frees it on all three of its exits, so this is an
oversight rather than a convention.

Nothing caught it because no test constructed a TcpSocketHandler and called
listen() in process until this branch added one, and LeakSanitizer -- which the
Linux asan job enables by default -- is unavailable on macOS. The new backlog
test turned the leak into a red CI leg:

    Direct leak of 64 byte(s) in 1 object(s) allocated from:
        #1 getaddrinfo
        #3 et::TcpSocketHandler::listen(et::SocketEndpoint const&)
           TcpSocketHandler.cpp:175
    SUMMARY: AddressSanitizer: 64 byte(s) leaked in 1 allocation(s).

Catch reported the test itself as passing; only the process exit code changed,
which is why ctest logged a failure with no visible reason.

Also logs the backlog listen() actually applied and warns when a configured
value is discarded, so an operator can tell what took effect, and notes in
et.cfg that Linux truncates the backlog to net.core.somaxconn -- easy to trip
over when raising it.

Testing:

Ubuntu 24.04 with -DSANITIZE_ADDRESS=ON: 161/161. Reverting only this file's
freeaddrinfo calls flips the backlog test's exit code from 0 to 1 with the
report above, so the cause is verified rather than inferred.

* Test the initial-payload deadline directly

The deadline was the point of an earlier commit and the one exit still
uncovered: INITIAL_PAYLOAD_TIMEOUT_DURATION is a compile-time constant, so a
test could only have reached it by waiting ten minutes.

Read it through a protected member that a test subclass can lower. Production
behaviour is unchanged, since the member is initialized from the same constant.

Testing:

Adds a third case to HandleConnectionTimeoutTest: a silent client, a one second
deadline, and neither the halt flag nor the connection's shutdown flag set, so
only the deadline can end the wait. The socketpair setup the two silent-client
cases share moves into a helper.

The fixture now stops listening on both pipes it opened. Nothing else did:
ServerConnection and UserTerminalRouter each listen in their constructor, and
TerminalServer::shutdown() only sets the halt flag, so every case was leaving
two listening sockets behind. It also checks mkdtemp's return before building a
string from it, since the emptiness check it replaces could never fire.

* Refuse a reconnect while one is in flight for that client

Taking the recovery out of classMutex frees the accept loop, but the recovery
still occupies the handler thread it runs on, and reconnects for one client
serialize on that connection's mutex. Overlapping attempts therefore each park a
worker for the length of every attempt ahead of them, and that pool is eight
threads wide and shared with every other client's handshake.

Measured against a real etserver: one live session, four silent reconnects
arriving every fifteen seconds for two minutes, and a fresh client attempting to
connect five times through that window.

    unpatched     hung 45s  hung 45s  13s  0s  0s
    accept fix    0s        0s        42s  1s  13s
    this commit   0s        0s        0s   0s  1s

A real client cannot overlap its own attempts, because pollReconnect() blocks in
its own half of the same handshake before it retries. An unauthenticated peer
can: a reconnect needs nothing but a client id, as #784 describes, so a handful
of sockets that answer nothing is enough to hold the pool.

Refusing costs nothing that waiting was buying. The refused socket is closed
before the live session is touched, so the victim keeps its own connection, and a
client that really is reconnecting comes back on its next attempt.

Testing:

A second case in AcceptStarvationTest wedges a recovery, then requires a second
reconnect for the same client to return within five seconds. Without this commit
it waits for the first one's socket timeout and the case fails on that deadline.
It also checks the refused peer sees RETURNING_CLIENT and then EOF, and that the
live session is still registered afterwards. The shared setup the two cases need
moved into a helper.

macOS: 162/162.
MisterTea pushed a commit that referenced this pull request Nov 17, 2026
… reconnect (#924)

* fix: reject a reverse tunnel with no source instead of aborting etserver

A reverse tunnel in the InitialPayload with neither a source nor an
environment variable reached STFATAL in PortForwardHandler::createSource(),
so any user who could start a session could abort etserver and end every
user's sessions. A failed mkdtemp() also built a std::string from NULL.

Reject such a tunnel before creating the directory, and turn the mkdtemp,
chmod and chown failures into runtime_errors, which the existing catch
reports to the client.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Michel Lind <[email protected]>

* fix: restrict reverse-tunnel socket paths to their owner

listenAtPath() called fchmod() on the socket descriptor after listen().
On Linux that changes the socket inode, not the bound path, so the path
kept umask-derived permissions and the chmod() fallback never ran. With
a permissive umask, other local users could connect to a reverse
tunnel's socket.

chmod() the path to 0700 after bind() and before listen(), fail if that
does not work, and remove the path on failure.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Michel Lind <[email protected]>

* fix: keep the user's supplementary groups when dropping privileges

Since #784, runAsUser() calls setgroups(1, &gid) with only the primary
group, so forwarding to a socket the user can reach only through a
group (docker.sock via the docker group, group-shared directories)
fails with EACCES.

Resolve the group list in the parent with getpwuid_r() and
getgrouplist(), since NSS is not safe in a child forked from a threaded
process, cap it at NGROUPS_MAX, and pass it to setgroups() in the child.
If the user cannot be looked up, keep only the primary group, as before.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Michel Lind <[email protected]>

* fix: connect to Unix sockets with a 3 s deadline

connectAtPath() did a blocking connect(). On Linux a listener whose
backlog is full and which never accepts blocks it forever, hanging the
session's thread in connectUnixAsUser and later etserver shutdown,
which joins that thread. PipeSocketHandler::connect() used to give up
after 3 s.

Connect non-blocking with a 3 s deadline, retrying on EAGAIN, which is
what Linux returns for a full backlog (nothing is left in progress).

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Michel Lind <[email protected]>

* fix: keep a partly read packet when a reconnect fails

When recover() fails, recoverClient() restored the old socket with
BackedReader::revive(), which clears partialMessage. If the live socket
was part way through a packet, the next read started mid-frame and the
client was disconnected. With the legacy handshake, a peer that knows
only the client id could trigger this.

Add BackedReader::reattach(), which restores the socket and keeps the
partial packet; a failed recover() never calls reader->revive(), so the
reader is otherwise unchanged. Also restore the writer under its
recoverMutex, as recover() does.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Michel Lind <[email protected]>

* test: avoid a GCC 16 -Warray-bounds false positive in BackedIOTest

The Fedora job failed to build BackedIOTest.cpp under -Werror:

  BackedIOTest.cpp:420: array subscript 'ErrnoReadHandler[0]' is partly
  outside array bounds of 'unsigned char [80]'

The BackedReader reattach test read the framed packet back with a virtual
handler->read() on an InMemorySocketHandler. GCC speculatively
devirtualized that call to ErrnoReadHandler::read, the only other read()
override in the file, and then warned that its err member lies past the
end of the smaller InMemorySocketHandler allocation.

Read the bytes back with a non-virtual InMemorySocketHandler::drain()
instead.

Co-authored-by: Cursor <[email protected]>

* fix: send packets buffered during a failed reconnect

recoverClient() detaches the writer before recover() takes its mutex. A
packet written in that window, or after a failed recover() releases the
mutex and before the old socket is restored, was only buffered: it took a
sequence number and a nonce but was never sent. Restoring the old socket
with revive() dropped it, so the client failed to decrypt the next packet
and had to reconnect.

Add BackedWriter::reattach(), which restores the socket and sends the
packets buffered while it was detached, in order, under the recover mutex.

Co-authored-by: Cursor <[email protected]>

* fix: bound the Unix connect poll by the remaining deadline

If connect() reports EINPROGRESS, connectAtPath() polled for a fresh
CONNECT_TIMEOUT_MS after already retrying EAGAIN for up to that long, so
the call could take twice the intended 3 s. Poll only for what is left of
the deadline.

Co-authored-by: Cursor <[email protected]>

* fix: cache each user's supplementary groups for 60 s

runAsUser() looked up the session user's groups (getpwuid_r and
getgrouplist, which can go to LDAP or sssd) on every forwarded Unix
connection, on the thread serving the session. Remember the result per
uid and gid for 60 s, looking up outside the cache lock so one slow user
does not stall the others. A group membership change takes effect within
a minute.

Co-authored-by: Cursor <[email protected]>

---------

Signed-off-by: Michel Lind <[email protected]>
Co-authored-by: Jason Gauci <[email protected]>
Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants