Skip to content

fix command injection in filename-driven render/preview handlers - #17803

Merged
kevinushey merged 5 commits into
mainfrom
bugfix/filename-command-injection
Jun 1, 2026
Merged

kevinushey merged 5 commits into
mainfrom
bugfix/filename-command-injection

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses rstudio/rstudio-pro#10989.

Summary

Two related changes hardening how RStudio constructs R commands for
filename-driven "run/preview/render" actions.

1. Escape interpolated paths (filename command injection).
Several handlers built an R command by concatenating a user-controlled
file path directly into a single-quoted R string literal, so a filename
containing a single quote could break out of the literal and inject R
code. Each interpolated path/stem/encoding is now escaped with
string_utils::singleQuotedStrEscape() (already used elsewhere for this
purpose). Covered sites:

  • Plumber "Run API" (SessionPlumberViewer.cpp)
  • R Presentation "Preview" (presentation/SlideRequestHandler.cpp)
  • HTML/knitr preview (SessionHTMLPreview.cpp)
  • Sweave and knitr weave (tex/SessionRnwWeave.cpp)
  • shinytest2 / testthat run and website render_site (build/SessionBuild.cpp)

While here, these sites were ported from boost::format/string
concatenation to fmt::format, the generated R is formatted
conventionally (spaces around =), and a string_utils::heredoc()
helper (with unit tests) was added so multi-line R templates can be
indented to match the surrounding source.

2. Confirm custom knit: render commands.
A document can specify a custom render command in its YAML knit: field,
which RStudio evaluates as R code at render time -- so opening an
untrusted document and clicking Knit/Preview could run arbitrary code
with no warning. This is execution-by-design rather than string
injection, so escaping does not apply. The render chokepoint now asks
the backend (via a new read-only get_custom_render_function RPC that
only parses the YAML, it does not evaluate it) whether the document's
render function is custom, and prompts for confirmation before running
it. RStudio's own defaults and derived render functions are known-safe
and skip the prompt; approval is remembered per source file for the
session.

Testing

  • New C++ unit tests for string_utils::heredoc() (StringUtilsTests.cpp).
  • New Playwright test (e2e/.../custom_knit_confirm.test.ts) asserting the
    custom-knit confirmation prompts, that declining runs nothing, that
    accepting runs the command, and that approval is remembered.
  • rstudio-core/rsession build and link; GWT compiles; the new e2e test
    passes on desktop.

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.
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).
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).
@kevinushey kevinushey added this to the Blue Plumbago milestone May 29, 2026
@posit-snyk-bot

posit-snyk-bot commented May 29, 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.

@kevinushey
kevinushey requested a review from gtritchie May 30, 2026 00:30
@gtritchie

gtritchie commented May 30, 2026 •

Copy link
Copy Markdown
Member

Review summary

The escaping half of this PR is solid and correct; the confirmation half has a few consistency gaps worth a decision before merge. Findings below were cross-checked against the actual knit: execution sink, the driver interpolation path, and the R parse-only guarantee.

Critical / High -- decide before merge

1. The confirmation gate fails open in three places (indeterminate -> "safe").
The gate lives entirely in the GWT client; the backend RenderRmd::start evaluates the knit: field with no independent confirmation check (SessionRMarkdown.cpp:629), so each client fall-through is the last line of defense:

  • SessionRMarkdown.cpp getCustomRenderFunction -- when .rs.getCustomRenderFunction errors, the code logs and returns an empty renderFunc; empty is in the known-safe set, so requires_confirmation = false (no prompt).
  • RmdOutput.java onError -- logs and calls doRenderRmd(event) anyway.
  • RmdOutput.java onResponseReceived -- null/missing requires_confirmation is treated as "no prompt."

Practical exploitability is lower than it first appears, because the same .rs.getCustomRenderFunction feeds both the gate and the backend sink, and malformed YAML is already tryCatch'd on the R side to "" (benign -- no custom function to run either). The realistic trigger is an R-level error (e.g. unreadable file, encoding failure). But the posture is still wrong for a security gate: the asymmetry favors failing closed (prompt on indeterminate -- a minor annoyance) over failing open (silent arbitrary-code execution). Suggest: on error/null, set requires_confirmation = true rather than proceeding.

2. Unescaped driver argument -- a parallel injection vector in a file this PR is hardening.
SessionRnwWeave.cpp:233: cmd += ", driver = " + driver. driver comes from a document % !Rnw driver = ... magic comment (driverForFile, line 432) and is interpolated unquoted as a bare R expression, so a value like RweaveLatex(); system("..."); f( injects when an untrusted .Rnw is compiled. The PR escapes file and encoding in this exact function but not driver. Quote-escaping won't fix it (unquoted context) -- needs allow-list/identifier validation, or an explicit decision that it's out of scope (with a code comment saying why).

Important

3. renderRmdSource path bypasses the gate. onRenderRmdSource calls the server directly and the backend runs the same knit:-evaluating flow with no confirmation. Currently latent (no live callers of renderRMarkdownSource), but it means the gate guards only one of two render entry points. Consider whether the gate belongs at the backend chokepoint (RenderRmd::start) for defense-in-depth.

4. The security primitive itself has zero test coverage. singleQuotedStrEscape() -- the function the entire injection fix relies on -- has no test anywhere in the tree, and now five sites depend on it for a security guarantee. A trivial unit test in StringUtilsTests.cpp with a malicious payload ('; system('rm -rf /') # -> quotes escaped; a\b -> backslash doubled) is the highest-value, lowest-cost regression guard in the PR. Likewise requiresRenderConfirmation() is pure and trivially testable but untested.

Suggestions

  • Per-session approval is keyed by file path only (RmdOutput.java customRenderConfirmed_). If the file at that path is replaced (git pull, external edit) with a malicious knit: after approval, no re-prompt occurs for the session. Narrow; keying on a hash of the knit: value would close it.
  • e2e test omits the known-safe / no-prompt path -- a regression that prompts on every ordinary knit wouldn't be caught. (Covered cheaply by a requiresRenderConfirmation unit test instead.)
  • heredoc() cosmetic: an over-indented all-whitespace interior line keeps trailing whitespace (StringUtils.cpp -- only shorter blank lines are cleared). Harmless for the static R snippets it's fed.

Recommended action

  1. Fail closed on the three indeterminate paths in finding Clone fail-Permission denied (publickey) #1 (toward prompting).
  2. Decide on the unescaped driver (Autocompletion of delimiters #2): validate or explicitly scope out with a comment.
  3. Add the singleQuotedStrEscape + requiresRenderConfirmation unit tests (PAM Session Prototype #4).
  4. Confirm the renderRmdSource decisions

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Feedback posted, some things worth looking at

- 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()
@kevinushey
kevinushey merged commit 4134f4b into main Jun 1, 2026
8 checks passed
@kevinushey
kevinushey deleted the bugfix/filename-command-injection branch June 1, 2026 22:32
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