Skip to content

Deny proxied connections to localhost ports owned by others - #18330

Merged
mbaynton merged 10 commits into
mainfrom
localhost-proxy-isolation
Jul 30, 2026
Merged

mbaynton merged 10 commits into
mainfrom
localhost-proxy-isolation

Conversation

@mbaynton

@mbaynton mbaynton commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Open source companion to https://github.com/rstudio/rstudio-pro/issues/11470 -- intent and approach are unchanged, see pro issue and PR. It's also reviewed over there.

I see the new unit tests didn't run as part of the PR actions because we don't build server_core. They do pass locally...

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

Adds lookupEstablishedSocketUid/verifyPeerUid, backed by a
NETLINK_SOCK_DIAG/inet_diag dump of the established server-side socket
for a loopback 4-tuple, plus a one-time probeSockDiagAvailable()
capability probe so enforcement sites can degrade gracefully when the
netlink syscall is blocked. This is the primitive rstudio-pro#11470's
port-proxy ownership checks will build on.

* Add post-connect peer UID verification hook to async client path

Introduces a no-op virtual verifyConnectedPeer() hook in core's
AsyncClient, invoked after connect (and TLS handshake) but before any
request bytes are written. LocalhostAsyncClient/LocalhostAsyncClientSsl
override it to enforce destination-port ownership via Step 1's
verifyPeerUid, guarded by the sock_diag availability probe and a
settable expectedPeerUid_ (sentinel -1 disables the check). Adds an
end-to-end gtest exercising the reject path on a UID mismatch.

* Enforce port ownership on rserver-side localhost proxy hop

Resolve the requesting user's UID via the cached userIdForUsername
helper and set it as the expected peer UID on LocalhostAsyncClient in
proxyLocalhostRequest, so the post-connect kernel-UID check (added in
Step 2) rejects /p/ and /p6/ requests to ports not owned by the
caller. Mirrors the existing "user not found is acceptable" carve-out
used for local-stream uid validation. Also updates the UrlPorts.cpp
trust-boundary comment to note that ownership is now enforced
separately from the port token's obfuscation.

* address review: fail closed on uid resolution error in /p/ proxy

The port-ownership check on /p/ and /p6/ is the sole access-control
boundary for an attacker-chosen, decoded target port -- unlike the
adjacent local-stream uid validation, whose target is derived from
the caller's own session context and so can never be steered to
another user's resource. Skipping the check on "user not found"
(permission_denied) left ownership enforcement disabled for that
one request regardless of which port it targeted, so a transient
uid-resolution failure (NSS/LDAP hiccup, cold per-process cache) at
request time -- not just a not-yet-provisioned account -- could
reopen the cross-user bypass this feature exists to close. Treat any
uid resolution error as fatal on this path.

* Enforce port ownership on Launcher-mode SessionProxy hop

SessionProxy self-checks its own effective uid via ::geteuid() against
the destination port owner before proxying, closing the launcher-mode
bypass around the /p/ and /p6/ ownership enforcement (rstudio-pro#11470).

* Add NEWS entry for portmapped app URL cross-user isolation fix

* Add e2e coverage for /p/ and /p6/ cross-user port isolation

Covers the rstudio-pro#11470 fix end-to-end: cross-user /p/ and /p6/
requests are rejected, while same-user access to one's own port still
succeeds.

* Return 403 instead of 500 when the port-ownership check rejects a request
@posit-snyk-bot

posit-snyk-bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

OS test environments are not well suited to run sessions (or start
arbitrary listeners even) as more than one user; this would have created
substantial headache for the OSS team who runs the tests directly on
their local machines.

This test will remain in rstudio-pro.
@github-actions

github-actions Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1899 0 365 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ desktop-linux 473 0 88 1
✅ desktop-macos 468 0 94 1
✅ desktop-windows 479 0 89 0
✅ server-linux 459 0 94 0
✅ setup 20 0 0 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit 97fe35310421628699bafd355d0462a8b013341a - Run #395

@mbaynton
mbaynton requested review from gtritchie and kevinushey July 23, 2026 18:39

@kevinushey kevinushey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overall design here is sound. The verification point (post-connect, pre-write, keyed to the actual established connection rather than a racy pre-connect scan) is the right one: the 4-tuple is pinned while our client socket is open, so there's no TOCTOU window, and SO_REUSEPORT can't be used cross-uid to steal a bound port. The fail-closed handling of uid-resolution errors -- with a good comment explaining why it deliberately diverges from proxyRequest()'s lenient "user not found is OK" path -- is correct, since the destination port is attacker-controlled on this path. Both hook sites are exception-wrapped (CATCH_UNEXPECTED_ASYNC_CLIENT_EXCEPTION), which matters because remote_endpoint() can throw.

That said, I don't think this can merge as-is; two issues below are blocking.

Blocking: breaks the macOS build

SocketOwnership.cpp unconditionally includes <linux/netlink.h>, <linux/sock_diag.h>, <linux/inet_diag.h> and is added unconditionally to SERVER_CORE_SOURCE_FILES. But server_core is not Linux-only: cmake/globals.cmake sets RSTUDIO_SERVER=TRUE for any non-Windows Development build, so every macOS dev build compiles it (verified locally on macOS -- linux/netlink.h doesn't exist there). The *Tests.cpp glob also picks up SocketOwnershipTests.cpp, and LocalhostAsyncClient.hpp now calls socket_utils:: functions from an inline method, so a CMake exclusion alone won't link.

Suggested fix: keep the netlink implementation under #ifdef __linux__ (or split the CMake sources) with a portable stub where probeSockDiagAvailable() returns false -- macOS rserver is dev-only, so degrading to no-enforcement there matches the PR's own graceful-degradation posture. Note the PR actions don't build server_core, so CI won't catch this.

Blocking: dual-stack listeners get falsely 403'd

Apps that listen on a dual-stack wildcard socket -- Node.js's default server.listen(port) binds :: with IPV6_V6ONLY=0, as do many Java apps -- accept a 127.0.0.1 connection on an AF_INET6 child socket whose addresses are v4-mapped (::ffff:127.0.0.1). Two consequences in lookupEstablishedSocketUid():

  • The AF_INET dump won't return that socket at all (the kernel's inet_diag dump filters on sk_family != sdiag_family), so the lookup fails and the request fails closed with 403.
  • Even an AF_INET6 dump wouldn't match, because isLoopbackDiagAddr(ipv6=true, ...) only accepts exactly ::1, not ::ffff:127.0.0.1.

So /p/ proxying to a perfectly legitimate, user-owned Node/Java app can break. Suggest: on a miss in the requested family, retry with an AF_INET6 dump accepting v4-mapped loopback (or dump both families and normalize mapped addresses). A test that binds :: dual-stack and connects via 127.0.0.1 would demonstrate this directly. If this was consciously scoped out in the pro review, it deserves a comment; as written it looks like an oversight.

Performance

verifyConnectedPeer() runs synchronous sendto/recvmsg netlink syscalls on the io_context strand and dumps all ESTABLISHED TCP sockets on the host per proxied request -- that's every asset fetch of every Shiny app, on servers that may have thousands of established sockets. Two cheaper options: an exact-match query (SOCK_DIAG_BY_FAMILY without NLM_F_DUMP, passing the full inet_diag_sockid -- the kernel's tcp_diag_get_exact path, one round trip), or an INET_DIAG_REQ_BYTECODE port filter on the dump. Relatedly, the comment "First draft of a pure async peer verification check in 662c4fc3..." references a commit that doesn't exist in this repo -- if async verification is planned follow-up, say so with a reachable reference; otherwise drop the comment.

Smaller points

  • 403 conflates mismatch with infrastructure failure: verifyPeerUid() tags every error -- including netlink transport failures and "socket vanished between connect and dump" -- with kPortOwnershipRejectedProperty, so transient infrastructure problems surface to the browser as "Not authorized to access the requested port". Fail-closed is right, but consider reserving 403 for the actual uid-mismatch/not-found cases and leaving genuine netlink errors on the 500 path.
  • Comment hygiene: several comments reference design artifacts that don't exist in this repo -- "(Decision 2)", "(research Q8)", "(eval P3)", "Step 6's e2e coverage". These are noise for future open-source readers; suggest trimming to self-contained "why" statements.
  • Duplication: verifyConnectedPeer() is duplicated verbatim between LocalhostAsyncClient and LocalhostAsyncClientSsl, differing only in the socket accessor. A small shared helper taking boost::asio::ip::tcp::socket& would keep the two from drifting.
  • The MSG_TRUNC handling is a nice catch (a truncated dump would otherwise be indistinguishable from "not found"), though the 8KB receive buffer also caps the kernel's dump batch size, so truncation should be rare in practice.

Tests

Coverage is genuinely good for this kind of code: positive/negative uid paths, real end-to-end LocalhostAsyncClient accept/reject wiring, IPv6 loopback with a sensible GTEST_SKIP guard, and the capability probe. Two caveats:

  • The ServerSessionProxyTests pair only exercises the getpwnam cache wrapper via the userIdForUsernameForTest() export -- thin value for the amount of scaffolding (test-only symbol in a public header), and the real decision logic in proxyLocalhostRequest() remains untested here.
  • No coverage for the dual-stack/v4-mapped case above.

Also: the UrlPorts.cpp doc update clarifying that obfuscation is not the security boundary is a welcome addition, and no NEWS.md entry is needed given this is an open-source companion to the pro change.

SocketOwnership.cpp unconditionally included <linux/netlink.h> and
friends, breaking the macOS build since server_core is compiled there
too (RSTUDIO_SERVER is set for non-Windows dev builds). Non-Linux
platforms now get a stub where probeSockDiagAvailable() returns false
and lookup/verify fail closed, matching the graceful-degradation
posture already used for restrictive Linux sandboxes.
@mbaynton

Copy link
Copy Markdown
Contributor Author

Nice find on

Blocking: dual-stack listeners get falsely 403'd

There's a lot of issues there and it's pretty broken as-is. Interesting other forms of review that this code has already passed did not catch this.

…ship check

Query NETLINK_SOCK_DIAG with an exact 4-tuple instead of dumping and
scanning every established TCP socket on the host, since this runs on
every request through the localhost proxy. This also incidentally fixes
dual-stack (IPV6_V6ONLY=0) listeners being invisible to the ownership
check: the kernel's dump path filters strictly by sk_family, but the
exact-match lookup path does not, and matches such sockets via their
IPv4-mapped address regardless of family (rstudio-pro#11470).
@mbaynton

Copy link
Copy Markdown
Contributor Author

Good review @kevinushey. I would have considered the NLM_F_DUMP performance issue to be blocking as well -- that's on me, it should have been using a direct lookup of the established socket matching source/dest ports. I've switched to that approach, and initially also added a separate fallback-to-IPv6 family query as well for the dual-stack single-listener case (TIL you can do that!), but it turns out you don't need it -- basically the matching logic in the kernel doesn't end up filtering on address family anyway so the first, targeted query will always find it. Tests that actually fire up listeners of all 3 types (IPv4, IPv6, and IPv4-mapped to v6) and successfully harvest the listner's UID are also included to prove that no fallback query is necessary.

@mbaynton
mbaynton requested a review from kevinushey July 24, 2026 16:23
@kevinushey

Copy link
Copy Markdown
Collaborator

Really nice change — the design decisions are well-reasoned and the in-code documentation is excellent. The exact-match netlink query (vs. a dump), the fail-closed handling on the attacker-controlled path, and the dual-stack v4-mapped coverage are all handled thoughtfully. Not blocking; a few small suggestions:

  • SocketOwnership.cpp — blocking netlink I/O: verifyPeerUid() does a synchronous sendto/recvmsg on the strand thread for every proxied request. Fast for a loopback query in practice, but the netlink socket has no SO_RCVTIMEO, so a pathological non-reply would hang the io thread rather than fail. Could we add a defensive receive timeout?

  • LocalhostAsyncClient.hpp — stray comment: the // First draft of a pure async peer verification check in 662c4fc3... line looks like leftover dev cruft — worth removing.

  • Fail-open when NETLINK_SOCK_DIAG is unavailable: I see this is a deliberate "availability over isolation" call, and it's logged once — but it means isolation silently doesn't apply in a locked-down seccomp/capability sandbox. Can we make sure that's called out in the operator-facing / release notes so hardened deployments know the enforcement can be disabled by their own sandboxing?

  • Duplication: the two verifyConnectedPeer() bodies (plain vs. SSL) are near-identical apart from socket() vs socket().next_layer(). Might be worth extracting a shared helper to avoid drift.

  • Minor/defensive: in readSingleDiagReply, consider a length check that nlmsg_len covers sizeof(inet_diag_msg) before dereferencing idiag_uid (kernel is trusted, so purely hardening).

mbaynton and others added 2 commits July 24, 2026 13:49
Set a 3s receive timeout on the socket-diag netlink socket so a stalled
or unresponsive kernel reply can't block a proxied request indefinitely;
a timeout is reported as a distinct, fail-closed error like any other
lookup failure. Setting the timeout itself is treated as best-effort:
if setsockopt() fails, log a warning and proceed without a timeout
rather than degrading enforcement over it (rstudio-pro#11470).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
roborev review of 2a2bf64 flagged that probeSockDiagAvailable()'s
result is cached for the process lifetime, so a transient SO_RCVTIMEO
timeout during the one-time probe would permanently fail-open instead
of fail-closed -- unlike an EPERM/EOPNOTSUPP rejection, a timeout says
nothing about whether the capability actually works. Treat it as
inconclusive (assume available) instead; per-request lookups still
time out and fail closed individually if the condition recurs.
@mbaynton

Copy link
Copy Markdown
Contributor Author

Added a socket timeout, not a bad idea.

The sha in the comment references the last commit in a line adding async support for netlink sockets that's pushed to pro (https://github.com/rstudio/rstudio-pro/commit/662c4fc3a046409df03667d89a4604ec001173fc).

NEWS will be added in workbench.

@kevinushey kevinushey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's solid

I verified these against the surrounding code rather than taking the comments' word for it:

  • The hook placement is safe on both paths. The plain-TCP path wraps verification in try/CATCH_UNEXPECTED_ASYNC_CLIENT_EXCEPTION on the strand; the SSL path's handleHandshake is already exception-guarded and strand-bound. A throwing remote_endpoint() (peer RST race) lands in handleUnexpectedError rather than escaping.
  • A rejection cannot trigger the reconnect-retry loop. retryConnectionIfRequired() only fires for connection-unavailable errors and requires a retry profile, which this client never sets. The rejection funnels cleanly to the error handler.
  • No bypass via other instantiation sites. The only open-source construction of LocalhostAsyncClient is the one this PR pins; redirects round-trip through the browser and get re-verified.
  • The exact-match (non-NLM_F_DUMP) query is the right call for a per-request check, and the dual-stack subtlety (v4-dialed connection to an IPV6_V6ONLY=0 listener) is both explained and covered by a dedicated test.
  • Fail-closed uid resolution in proxyLocalhostRequest is correctly stricter than proxyRequest's, and the comment explaining why the two differ (attacker-controlled destination vs. self-scoped stream path) is exactly the kind of comment that should exist.
  • The new test file is picked up automatically (server_core/CMakeLists.txt globs *Tests.cpp), and RSTUDIO_UNIT_TESTS_ENABLED is a real compile definition (cmake/globals.cmake:117), so the #ifdef'd test hook compiles as intended.

Findings

1. The three lookup tests fail (not skip) on macOS. cmake/globals.cmake enables unit tests on all builds unless explicitly disabled, and server_core builds on macOS dev machines (some of us run rserver dev builds locally on macOS). On non-Linux, lookupEstablishedSocketUid() returns not_supported, so LooksUpUidOfEstablishedLoopbackSocket, the IPv6 variant, and the dual-stack variant all hard-fail their EXPECT_FALSE(error) assertions. The probe-gated tests skip gracefully, but these three need an #ifdef __linux__ guard or a GTEST_SKIP() when the lookup reports not_supported.

2. The 403 mapping can be shadowed by the 503 branch above it. The "no established socket for requested 4-tuple" rejection is systemError(no_such_file_or_directory, ...), and isConnectionUnavailableError() (SocketUtils.hpp:100) matches exactly that code. Since the new block in handleLocalhostError() sits below the isConnectionUnavailableError && requiresSession -> 503 branch, a rejected request carrying X-RStudio-Session-Required reports 503 instead of 403. Still denied, so no security impact, but the tagged property is definitive -- checking it first in handleLocalhostError() is both more correct and more robust against future reordering.

3. Netlink reply authenticity (hardening, optional). readSingleDiagReply() doesn't capture msg_name to verify the sender is the kernel (nl_pid == 0) nor check nlmsg_seq. Unprivileged processes can't unicast to another socket's portid without CAP_NET_ADMIN, so this isn't exploitable in practice, but a two-line sender check is cheap defense-in-depth for security-enforcement code.

4. Deployment fail-open is worth double-checking with the pro side. When probeSockDiagAvailable() returns false (restrictive seccomp, non-Linux), enforcement silently disables with a single log line ("Decision 2" -- availability over isolation). That's a documented, deliberate choice, but it means a locked-down container profile quietly restores the old cross-user behavior. Fine if the pro docs cover it; flagging so it's a conscious sign-off.

Behavioral trade-off to surface (not a defect)

Cross-uid localhost services become unreachable via /p/ with no escape hatch in this PR: root-owned docker-proxy port publishes (-p 127.0.0.1:8080:...), system services, or any supervisor-owned listener now 403 even for the user who launched them. That's the PR's stated intent, but it will break some real workflows (rootful Docker is the one users will hit). Two things follow:

  • If the pro PR includes a config escape hatch or admin documentation, consider whether open-source rserver.conf should get the same.
  • NEWS.md: the companion-PR convention says skip, but this changes open-source Server behavior in a user-visible, workflow-breaking way -- I'd argue this one deserves an entry (or at least release-note coverage somewhere open-source users will see).

Style nits

  • Several new LOG_WARNING_MESSAGE(... + ... + ...) sites; we prefer the format-string macros (WLOGF("Refusing localhost proxy to port {}: {}", ...)).
  • The mid-function comment // First draft of a pure async peer verification check in rstudio-pro 662c4fc3... reads as a leftover work-note; either state the actual decision ("a fully async version was drafted in pro ; synchronous chosen because ...") or drop it.
  • Comments reference pro-internal artifacts that open-source readers can't resolve: "(Decision 2)", "(research Q8)", "Step 6's e2e coverage".
  • verifyConnectedPeer() is duplicated verbatim between LocalhostAsyncClient and LocalhostAsyncClientSsl; a shared free helper taking the tcp::socket& (plain socket() vs socket().next_layer()) would remove the copy. Precedent for duplication exists in this file, so this is optional.
  • ServerSessionProxy.cpp uses kPortOwnershipRejectedProperty via the transitive include through LocalhostAsyncClient.hpp; a direct #include <server_core/SocketOwnership.hpp> would be more robust.
  • Trailing whitespace in the IPv6 test comment (// differs from AF_INET. ).

Verdict

The security design is sound and the implementation is careful -- the fail-closed reasoning, strand/exception safety, and the dual-stack netlink subtlety are all handled correctly. I'd ask for: the non-Linux test guards (finding 1, will bite macOS dev builds), the 403-ordering fix (finding 2, small), and a decision on the Docker/cross-uid escape hatch + NEWS question before merge. The rest is take-it-or-leave-it polish.

kevinushey and others added 4 commits July 29, 2026 19:13
- skip the three netlink lookup tests on non-Linux platforms, where
  lookupEstablishedSocketUid() reports not_supported and the tests
  would hard-fail (e.g. macOS dev builds of rserver)
- check the port-ownership-rejected property before the
  connection-unavailable 503 mapping in handleLocalhostError(): the
  'no established socket' rejection also matches
  isConnectionUnavailableError(), which shadowed the 403 for requests
  carrying X-RStudio-Session-Required
- verify NETLINK_SOCK_DIAG replies come from the kernel (nl_pid == 0)
  and echo the request sequence number, as cheap defense-in-depth for
  enforcement code
- share verifyConnectedPeer() between LocalhostAsyncClient and
  LocalhostAsyncClientSsl via a common helper
- prefer WLOGF over string-concatenating LOG_WARNING_MESSAGE at new
  logging sites; drop work-note comments referencing pro-internal
  artifacts; include SocketOwnership.hpp directly in
  ServerSessionProxy.cpp
New boolean configuration option, defaulting to on, allows
administrators to disable this check and revert to the original behavior
in case they are running in some nonstandard environment where it
disrupts an existing workflow.

@kevinushey kevinushey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@mbaynton
mbaynton merged commit 072bdaf into main Jul 30, 2026
27 checks passed
@mbaynton
mbaynton deleted the localhost-proxy-isolation branch July 30, 2026 18:15
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.

3 participants