Repository navigation
Deny proxied connections to localhost ports owned by others - #18330
Conversation
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
✅ Snyk checks have passed. No issues have been found so far.
💻 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.
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
kevinushey
left a comment
There was a problem hiding this comment.
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" -- withkPortOwnershipRejectedProperty, 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 betweenLocalhostAsyncClientandLocalhostAsyncClientSsl, differing only in the socket accessor. A small shared helper takingboost::asio::ip::tcp::socket&would keep the two from drifting. - The
MSG_TRUNChandling 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
ServerSessionProxyTestspair only exercises thegetpwnamcache wrapper via theuserIdForUsernameForTest()export -- thin value for the amount of scaffolding (test-only symbol in a public header), and the real decision logic inproxyLocalhostRequest()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.
|
Nice find on
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).
|
Good review @kevinushey. I would have considered the |
|
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:
|
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.
|
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
left a comment
There was a problem hiding this comment.
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_EXCEPTIONon the strand; the SSL path'shandleHandshakeis already exception-guarded and strand-bound. A throwingremote_endpoint()(peer RST race) lands inhandleUnexpectedErrorrather 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
LocalhostAsyncClientis 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 anIPV6_V6ONLY=0listener) is both explained and covered by a dedicated test. - Fail-closed uid resolution in
proxyLocalhostRequestis correctly stricter thanproxyRequest'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.txtglobs*Tests.cpp), andRSTUDIO_UNIT_TESTS_ENABLEDis 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.confshould 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 betweenLocalhostAsyncClientandLocalhostAsyncClientSsl; a shared free helper taking thetcp::socket&(plainsocket()vssocket().next_layer()) would remove the copy. Precedent for duplication exists in this file, so this is optional.ServerSessionProxy.cppuseskPortOwnershipRejectedPropertyvia the transitive include throughLocalhostAsyncClient.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.
- 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.
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
NEWS.md