Skip to content

PAM Session Prototype - #4

Closed
nicelio wants to merge 2 commits into
rstudio:masterfrom
nicelio:1b310612b8f08d0caec2154932104f2f81e1965d
Closed

nicelio wants to merge 2 commits into
rstudio:masterfrom
nicelio:1b310612b8f08d0caec2154932104f2f81e1965d

Conversation

@nicelio

@nicelio nicelio commented Jul 29, 2011

Copy link
Copy Markdown

Perhaps the PAM session API can be accessed like this. It seems to work with AppArmor enabled.

@nicelio

nicelio commented Jul 29, 2011

Copy link
Copy Markdown
Author

Of course, the conversation function will only support a single password prompt. A fully functional conversation function would require dynamically changing the login prompt on the client side.

@jjallaire

Copy link
Copy Markdown
Member

Thanks for taking a shot at this. There are a couple of sticky issues we are still going to have to figure out to make this work:

(1) The fork prior to calling PAM is not necessary on Ubuntu however is necessary on RedHat (because a setuid process which starts as root and then drops priv can't restore root and call PAM on RedHat -- no idea why). So to make this work on RedHat we'll need to preserve the fork and (somehow) still have access to the PAM session handle in the rserver process.

(2) When to end the session: sign out almost never gets called (it's an explicit user gesture which is optional -- much more common will be the user simply closing their browser). What we really need to do is track the status of the underlying rsession process from within rserver and then end the session then. Note that rsession can exit either because the user quits or due to suspending (after the admin specified timeout -- defaults to 120 minutes). This is further complicated by the fact that rserver is intended to be "stateless" (it can be shot or restarted at any time without affecting the proper behavior of the system). If the rserver exits while it owns outstanding PAM session handles then these sessions would "leak" (e.g. the home directory would stay mounted).

The above two considerations lead me to think that we might need a dedicated long-lived process for doing PAM auth and managing session lifetimes. Not sure if we need to go to this extent but if need be we certainly will.

Understand you are eager to get this working and I think your solution will work on Ubuntu and if you assume that users must explictly sign out to end their session (could prove a difficuilt idiom to train for / enforce). We are hoping to address this issue with a fully robust solution in the not too distant future.

@jjallaire jjallaire closed this Sep 20, 2011
@alaimos alaimos mentioned this pull request Apr 24, 2020
4 tasks done
gtritchie added a commit that referenced this pull request Aug 6, 2020
On Centos7 (Desktop), unit tests were failing because global static initialization was causing access to an uninitialized string.

Fix by wrapping the static strings in functions.

The trigger is here: https://github.com/rstudio/rstudio/blob/e6fd9fd85f9088c13e8b2c5b78176111b4f2b485/src/cpp/core/LogOptions.cpp#L61

The crash stack was:
```
#0  0x000055ed09fbbdbe in std::string::size (this=0x55ed0b7d5188 <rstudio::core::(anonymous namespace)::s_homePathLeafAlias>)
    at /opt/rh/devtoolset-7/root/usr/include/c++/7/bits/basic_string.h:3817
#1  0x000055ed09fdc60c in std::operator==<char> (__lhs="~/.local/share", __rhs=<error reading variable: Cannot access memory at address 0xffffffffffffffe8>)
    at /opt/rh/devtoolset-7/root/usr/include/c++/7/bits/basic_string.h:6007
#2  0x000055ed0a97ce4c in rstudio::core::FilePath::resolveAliasedPath (in_aliasedPath="~/.local/share", in_userHomePath=...) at /src/src/cpp/shared_core/FilePath.cpp:476
#3  0x000055ed0a832e7f in rstudio::core::system::xdg::(anonymous namespace)::resolveXdgDir (envVar="XDG_DATA_HOME", defaultDir="~/.local/share", user=..., homeDir=...)
    at /src/src/cpp/core/system/Xdg.cpp:97
#4  0x000055ed0a833213 in rstudio::core::system::xdg::userDataDir (user=..., homeDir=...) at /src/src/cpp/core/system/Xdg.cpp:135
#5  0x000055ed0a8972ea in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at /src/src/cpp/core/LogOptions.cpp:61
#6  0x000055ed0a89740c in _GLOBAL__sub_I_LogOptions.cpp(void) () at /src/src/cpp/core/LogOptions.cpp:347
#7  0x000055ed0aa9580d in __libc_csu_init ()
#8  0x00007f948396c4e5 in __libc_start_main () from /lib64/libc.so.6
#9  0x000055ed09fb44f5 in _start ()
```
@kevinushey kevinushey mentioned this pull request Nov 15, 2022
4 tasks done
kevinushey added a commit that referenced this pull request Jun 1, 2026
)

* fix RCE via filename command injection in run/preview handlers

Escape user-controlled file paths before interpolating them into R
command strings, so that a filename containing a single quote cannot
break out of the string literal and inject arbitrary R code. Covers the
Plumber "Run API", R Presentation "Preview", HTML/knitr preview, Sweave
and knitr weave, shinytest2/testthat run, and website render_site
command paths.

While here, port these sites from boost::format / string concatenation
to fmt::format, format the generated R conventionally (spaces around
operators), and use multi-line raw-string templates. Add a
string_utils::heredoc() helper that strips the common leading indent
from a raw string so embedded R code can be indented to match the
surrounding source.

Addresses rstudio/rstudio-pro#10989.

* confirm before running a document's custom knit render command

An R Markdown document can specify a custom render command via the
`knit:` field in its YAML front matter. RStudio evaluates that value as
R code when rendering (RenderRmd::start), so opening an untrusted
document and clicking Knit/Preview can execute arbitrary code with no
warning.

Add a confirmation prompt: before honoring a custom render command, the
frontend (the single render chokepoint in RmdOutput) asks the backend
whether the document's render function requires confirmation. The new
get_custom_render_function RPC only parses the YAML front matter (it
does not evaluate the knit: field) and reports the render function plus
whether it is custom. RStudio's own defaults and derived render
functions (rmarkdown::render/run/render_site, bookdown/pkgdown/blogdown/
xaringan, quarto serve/render) are known-safe and skip the prompt. The
user is prompted once per source file per session.

Relates to rstudio/rstudio-pro#10989 (Amazon issue #4).

* test(e2e): confirm prompt before running a custom knit command

Adds a Playwright test for the custom `knit:` render confirmation: a doc
whose knit: field is a function writing a marker file is used to assert
that Knit prompts first, that declining runs nothing, that accepting
runs the command, and that the approval is remembered for the session.

Relates to rstudio/rstudio-pro#10989 (Amazon issue #4).

* fixup

* address PR review feedback for filename-injection hardening

- fail closed when the document render function can't be determined:
  getCustomRenderFunction sets requires_confirmation on R error, and the
  client confirms on null/missing/error rather than rendering silently
- validate the Sweave `driver` magic comment against an allow-list, since
  it is interpolated as a bare R expression and cannot be quote-escaped
- re-key per-session custom-render approval on the command value, so a
  changed knit: command (e.g. file replaced on disk) re-prompts
- document why renderRmdSource bypasses the client confirmation gate
- add unit tests for singleQuotedStrEscape and requiresRenderConfirmation
- collapse over-indented blank lines in heredoc()
gtritchie added a commit that referenced this pull request Jun 2, 2026
* Add Windows ConPTY migration design spec

Temporarily un-ignores docs/superpowers to allow committing the spec
and forthcoming plan; .gitignore and these docs will be reverted during
final cleanup.

* Refine ConPTY spec: lifecycle, backpressure, shutdown contract

Address roborev design review: final-output drain before onExit, writer
thread for input, bounded output buffer with backpressure, bounded
deadlock-free shutdown, race guards, failure-path cleanup, move
persistence bump into the integration phase, resolve CUSTOM-shell replay,
and narrow the temporary .gitignore exception to specs/ and plans/.

* Harden ConPTY spec shutdown/backpressure lifecycle

Resolve the shutdown-while-paused deadlock: stop() wakes the
backpressure-paused reader (stopped_ + notify outCv_) so drain/close
cannot hang and final output is not lost. Writer abandons queued input
on stop (clears queue, no resume). Bound the input queue with
reject-on-overflow. Reuse the bounded teardown for partial-startup
failures after CreateProcess. Surface writer errors via poll(). Scope
tuning constants and the full test enumeration to the plan; Ctrl+C stays
FIFO (unchanged from today).

* Harden ConPTY spec thread lifetime and race safety

Address review job 45: never detach the writer (CancelSynchronousIo
unblocks it for a reliable join); closer thread captures only the HPCON
so detach is the use-after-free-safe last resort; cap the output buffer
during shutdown with a logged truncation; make stopped_/abandon_ atomic;
launch reader/writer before CreateProcess to close the failure window;
scope the lossless-final-output guarantee to normal shutdown; update the
class sketch (abandon_, writerError_, byte accounting).

* Add Windows ConPTY implementation plan

* Harden plan: teardown ordering, EOF, writer errors, single-use lifecycle

Address roborev review job 47: closer-first teardown so ClosePseudoConsole
breaking both pipes is the reliable unblock (with repeated-cancel backstop
for the writer TOCTOU and a single post-timeout cancel for the reader, never
closing its handle under it); add ConPty::closeInput() so PTY stdin EOF is
delivered; lock stateMutex_ in setSize; reject ConPty reuse after stop;
surface async writer errors via takeWriterError() each poll tick; fold the
console08 persistence bump into the atomic swap commit. Also introduce
teardownLocked() in phase 1a as the single teardown path so the writer thread
is always joined.

* Plan: guarantee bounded teardown joins and persistent writer-exit state

Address roborev review job 48: give the reader/writer teardown a bounded
escalation ladder (closer breaks pipe -> CancelSynchronousIo -> last-resort
close-our-handle) so join() can never hang even if the closer stalls and a
cancel misses; document why closing our own handle is safe as the final
teardown-only resort. Separate persistent writerExited_ (rejects further
writeInput so input is never queued to a dead writer) from the report-once
writerError_ that takeWriterError() clears. Replace the non-deterministic
writer-error test with a deterministic input-rejection-after-EOF test.

* Plan: bound teardown via cancel-loop, drop unsafe handle-close

Address roborev review job 49: remove the last-resort close-our-handle
step (closing a handle under another thread's in-flight I/O is the
handle-reuse race earlier reviews flagged; ConPTY's synchronous-handle
requirement rules out cancelable overlapped I/O). Instead guarantee bounded
joins via repeated CancelSynchronousIo, which always unblocks a thread in
cancellable synchronous I/O; the writer loop-cancels, the reader drains
cleanly first then falls back to the same loop. Handles are closed only
after the joins. Document why deterministic writer-WriteFile-failure
injection is declined (would need a production test seam) and keep the
deterministic input-rejection-after-EOF test.

* Record Phase 0 POC results and CreateProcess guardrails

Phase 0 empirically validated the ConPTY contract on Windows: the build
approach (dynamic kernel32 load under _WIN32_WINNT=0x601, attr 0x00020016)
compiles and resolves; routing works with EXTENDED_STARTUPINFO_PRESENT +
clean std handles + handle-close-order even when the host owns a console;
a confound experiment isolated std-handle redirection (STARTF_USESTDHANDLES)
as the real prior-failure cause, not console ownership (no FreeConsole
needed); ClosePseudoConsole + a draining reader tears down non-cooperative
children in single-digit ms. Add guardrails to launchChild against
DETACHED_PROCESS/CREATE_NO_WINDOW/STARTF_USESTDHANDLES.

* Add ConPty class: dynamic loader, start, reader, basic stop

* Fix buildEnvBlock empty-environment double-null in plan

An empty Unicode environment block must still be two nulls; the prior
single-null could make CreateProcessW read past the buffer (roborev job 52
finding #4).

* Complete ConPty: backpressure, writer/input queue, hardened teardown

* Make StartSpawnsChildAndEchoes deterministic (avoid fast-exit attach race)

* Swap Windows PTY backend from winpty to ConPty

* Use synchronous winpty-parity writeInput; drop async writer

Removes the async writer thread, input queue, and cap that could silently
drop terminal input on overflow (roborev job 56). writeInput now does a
blocking WriteFile on the caller thread, matching winpty. Simplifies
teardown (no writer to join). Bump kConsoleDir to console08 only on Windows.

* Synchronize ConPty input handle against concurrent teardown

Terminal input may arrive on the websocket thread while stop()/closeInput()
close hInputWrite_ on the session thread. Guard the handle with a dedicated
inputMutex_; teardown closes the pseudoconsole first so an in-flight WriteFile
returns before the handle is closed under the lock (deadlock-free). Also drop
an unused iostream include. (roborev job 57)

* Write ConPty input on a duplicated handle outside the lock

writeInput held inputMutex_ across the blocking WriteFile, so closeInput()/
teardown could block behind a stalled write. Duplicate the handle under the
lock and write on the duplicate outside it, so handle close never waits and
there is no handle-reuse race. Add a concurrent write/closeInput watchdog
test. (roborev job 58)

* Remove winpty fields from Pseudoterminal and the --external-winpty-path option

The Windows terminal now uses ConPTY, so the winpty path/plainText/conerr
Pseudoterminal fields and the external-winpty-path session option are dead.
Trim the struct, update the terminal construction, drop the option, and
regenerate SessionOptions.gen.hpp.

* Remove external-winpty-path from rdesktop-dev.conf

The --external-winpty-path option was removed, and the session option
parser rejects unregistered options, so leaving this entry would break
dev desktop session startup. (roborev job 60)

* Remove winpty from the build system and dependencies

The Windows terminal now uses native ConPTY, so drop the winpty CMake
include/install wiring, the install-dependencies fetch, the vendored
winpty archive, and its license attribution.

* Re-enable terminal buffer replay for Windows shells

ConPTY emits clean VT sequences (unlike WinPty's screen-scraped output), so
recorded terminal buffers now replay faithfully on reconnect for all shell
types. Always allow reload in shellSupportsReload().

* Remove dead createdByApi terminal plumbing

shellSupportsReload() now always returns true after the ConPTY migration, so
the createdByApi flag (threaded through SwitchToTerminalEvent, TerminalPopupMenu,
TerminalTabPresenter, TerminalPane, TerminalDeckPanel, and TerminalSession) is no
longer read anywhere. Remove the field, constructor params, event accessor, and
the method parameters that carried it. (roborev job 63)

* Add NEWS entry for ConPTY terminal backend migration

* Fix ConPTY terminal: child stole rsession's redirected std handles

RStudio Desktop launches rsession from the Electron GUI with its std handles
redirected to pipes; the ConPTY child inherited those by value instead of
binding to the pseudoconsole, so terminals showed a blank cursor with no
output or echo. Clear the host std handles across CreateProcessW so the child
attaches to the pseudoconsole, then restore them. Add a regression test that
spawns with the host std handles redirected to a file. (#3798)

* Use per-child NULL std handles for ConPTY attach (no global SetStdHandle)

Replace the process-global SetStdHandle(NULL)+restore around CreateProcess
(which could race other threads/spawns) with a per-child fix: give the child
explicit NULL std handles via STARTF_USESTDHANDLES so it cannot inherit
rsession's redirected std handles by value and instead attaches to the
pseudoconsole. Verified to route output and accept input. (roborev job 66)

* Strip ConPTY startup clear from restarted terminal output

A restarted terminal's ConPTY host emits a one-time screen clear (CSI 2J
followed by a cursor home) when the new shell starts up
(microsoft/terminal#4252). For shells whose scrollback we replay on
reconnect (e.g. Git Bash), that clear was persisted into the replayable
buffer, so replaying it wiped the restored history -- the terminal
flashed the old output then went blank.

Strip the clear (and its accompanying SGR reset and cursor home) from the
restarted shell's first output, so the fresh prompt follows the preserved
history inline. The strip is Windows-only, one-shot per restart, and
applies only to shells that keep their buffer for replay; cmd/PowerShell
already delete their buffer on restart and are unaffected. Other
platforms are untouched (their PTYs emit no such clear).

* Make ConPTY restart-clear strip chunk-safe and first-match-only

Addresses review feedback on the previous commit:

- The conhost startup clear can be split across output chunks; a regex
  run on a single chunk could miss it and persist the destructive bytes.
  Accumulate the restarted shell's initial output and resolve the clear
  across chunk boundaries (holding output until the frame is complete or
  a bound is hit) before buffering or forwarding it.

- Strip only the first clear rather than every match, so a legitimate
  later clear (e.g. a real `clear`) in the same output is preserved, and
  clear the pending flag once resolved so it can't strip a future clear.

Unit tests cover inline stripping, a clear split across chunks, and that
only the first clear is removed.

* Bound ConPTY restart-clear hold window and flush on exit

Addresses review feedback: if a restarted shell emitted little output
and never the expected clear, the previous logic could withhold output
indefinitely (hiding the prompt) and drop the held bytes if the shell
exited.

Bound the hold to a small number of output callbacks; once the window
closes the buffer is flushed (stripping a complete clear if present, but
never withholding further). Also flush any held output from onExit() so
nothing is lost when the shell exits before the clear resolves.

* Forward restart output once content appears, not on a timer

Addresses review feedback: bounding the hold by output-callback count
didn't bound elapsed time -- a restarted shell that emitted a short
prompt without a clear and then waited for input would keep that prompt
hidden, since no further callback arrived to close the window.

Instead, hold output only while it is purely the leading control
sequences that precede the clear (where a clear may still arrive). As
soon as real content (printable text or an OSC title) appears with no
clear, forward immediately. Holding is therefore transient -- the
conhost startup frame is emitted contiguously -- and visible content is
never withheld waiting for output that will not come. The byte bound and
onExit flush remain as backstops.

* Bound ConPTY restart-clear stripping with an elapsed-time window

Addresses review feedback: with only a callback-count/byte bound, a
restarted shell that emitted just leading control sequences and then
idled could keep stripping enabled indefinitely, risking a later
user-issued clear being mistaken for the startup clear.

Record a short deadline (a few seconds) when the restart begins. Once it
elapses, any held output is flushed unchanged and stripping stops, so a
later clear is never affected. Visible content already flushes
immediately (it is never part of the leading frame), and onExit still
flushes anything held, so the deadline only bounds the rare
control-only idle case.

* Strip ConPTY restart clear without buffering output

Replace the cross-callback output-buffering approach (which had to defend
a clear split across output reads) with a simple per-chunk strip. Each
buffering variant introduced its own edge -- byte/callback bounds, idle
stalls, withheld output -- because it withheld output waiting for a frame
that the reader already delivers whole.

Now: within a short window after restart, strip the first complete clear
from output and forward immediately, never withholding. Stop once the
clear is stripped or the window elapses, so a later user clear is
unaffected. Mode-sets and the clear arriving in separate chunks are still
handled (mode-sets forward harmlessly; the clear is stripped when it
arrives). Only a clear split mid-escape-sequence is not handled, which
the reader's whole-write delivery makes impractical.

* Stop ConPTY restart-clear strip once visible output appears

If a restarted shell's first output is a prompt with no startup clear,
stripping previously stayed armed until the deadline, so a user-issued
clear in that window could be removed. Now, as soon as output containing
visible content (printable text or an OSC) is forwarded without a clear,
stop stripping -- the startup clear is absent. Combined with stopping
after the clear is stripped (the normal case) and the deadline backstop,
a later user clear is never affected. Still no buffering.

* Strip ConPTY restart clear only when preceded by leading control

If a prompt and a user-issued clear were coalesced into one output
callback, the previous code stripped the first clear it found -- removing
the user's clear. Now a clear is stripped only when everything before it
in the chunk is leading control output (mode-sets), which is true only
for the conhost startup clear; a clear that follows visible content is a
user clear and is left intact. Adds a same-chunk prompt-plus-clear test.

* Keep cmd/PowerShell terminal buffer for reload on restart

Command Prompt, PowerShell, PowerShell Core and (on Windows) custom
shells had their saved buffer deleted on restart, a WinPty-era workaround
from when those shells could not reload. The frontend now reports every
shell as reloadable, so deleting the buffer left nothing to replay -- the
terminal came back empty.

Under ConPTY these shells emit clean VT and replay like any other, so
keep their buffer on restart and arm the conhost startup-clear strip for
them as well. This also makes the backend consistent on non-Windows,
where PowerShell Core buffers were likewise being discarded.

* Disable terminal buffer reload for cmd and PowerShell

Command Prompt and PowerShell repaint their startup screen with absolute
cursor positioning -- PowerShell's PSReadLine redraws its whole banner
and prompt on the reconnect resize -- which does not compose with
replayed scrollback: the restored output is preserved but the fresh
prompt lands in the middle of it. These shells never reloaded their
buffer under winpty either, so keep reload disabled for them
(shellSupportsReload returns false; the backend deletes their buffer on
restart). Git Bash and other shells that position with relative line
feeds still reload and keep the conhost startup-clear strip. Corrects the
NEWS entry, which had claimed cmd/PowerShell scrollback restore.

* Reload cmd/PowerShell buffer except on restart

Returning false outright for cmd/PowerShell also suppressed the initial
replay an API-created terminal needs: such a terminal can emit its banner
and prompt before the UI attaches, and those bytes live only in the saved
buffer. The mid-output problem is specific to restart (a new shell's
absolute-positioned repaint layered over restored content), so reload
cmd/PowerShell unless the process was restarted. That still shows an
API-created terminal's initial output and same-shell reconnect scrollback
while suppressing the broken restart case (where the backend also deletes
the buffer).

* Remove ConPTY planning docs; restore docs/superpowers gitignore

These internal design/plan docs were committed temporarily by relaxing
the docs/superpowers ignore rule. Restore the single ignore line and
drop the docs so they are not part of the change.

* Harden ConPTY output and lifecycle error handling

Address PR review findings on the ConPTY backend:

- Surface the readOutput() error on the on-exit drain instead of
  dropping it, matching every other call site.
- Salvage bytes delivered alongside a terminating read error/EOF and
  log genuinely unexpected reader-loop failures even when n > 0.
- Track and report the dropped-byte count when a forced shutdown
  truncates output, replacing the context-free warning.
- Read hPC_ under stateMutex_ in running() so the lifecycle state is
  observed consistently from any thread.
- Clamp terminal dimensions to SHRT_MAX before the COORD cast so an
  absurd size cannot wrap negative.
- Reject a null pProcess in start() before dereferencing it.
- Drop stale implementation-plan and removed-winpty references from
  comments.

* Expand ConPTY test coverage

Address the PR review's test-gap findings:

- Pin PROMPT in the prompt-waiting tests so the cmd prompt
  deterministically ends in '>', removing a silent hang-then-proceed
  flake when the runner has a custom PROMPT.
- Add reuse-after-stop rejection, readOutput-after-stop, and setSize
  (live then post-stop) lifecycle tests.
- Add environment-block and working-directory round-trip tests.
- Add a cross-chunk startup-clear strip test exercising the
  keep-watching path across successive chunks.
- Drop stale plan references from test comments.

* Fix teardown deadlock from synchronized running()

teardownLocked() runs while holding stateMutex_, and its idempotent
short-circuit called running(), which now re-locks the same
non-recursive mutex. The first teardown short-circuits before that call
(stopped_ was false), but a repeat teardown -- the destructor after an
explicit stop() or a failed start -- evaluated running() and deadlocked.
Read hPC_ directly instead, as start() and setSize() already do.
@gtritchie gtritchie mentioned this pull request Oct 27, 2026
2 of 4 tasks
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