Skip to content

tweaks to findProgramOnPath implementation - #9620

Merged
kevinushey merged 5 commits into
mainfrom
feature/find-program-on-path-fixups
Jul 21, 2021
Merged

kevinushey merged 5 commits into
mainfrom
feature/find-program-on-path-fixups

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses #9608.

Approach

  • Use separate POSIX + Windows implementations
  • On POSIX, verify the requested file is executable
  • On Windows, search for a default set of "executable" extensions (if the supplied program appears to have no extension)

Automated Tests

Unit tests included.

QA Notes

N/A

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

@kevinushey
kevinushey requested a review from jmcphers July 20, 2021 21:29
Comment thread src/cpp/core/system/PosixSystem.cpp Outdated
// verify that the file exists and is executable
struct stat sb;
int status = ::stat(candidatePath.getAbsolutePath().c_str(), &sb);
if (status || (sb.st_mode & S_IXUSR) == 0)

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.

Edge case: do we need to check S_IXOTH?

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Some other thoughts:

I think because we want to respect the effective user ID, we probably want to stick to using stat() here rather than access(). Is that correct? (We could also use eaccess() here: https://linux.die.net/man/3/euidaccess)

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Made a change using ::faccessat() since that appears to be the most portable solution.

@kevinushey
kevinushey merged commit 2817de9 into main Jul 21, 2021
@valerie-rstudio
valerie-rstudio deleted the feature/find-program-on-path-fixups branch January 21, 2022 17:54
kevinushey added a commit that referenced this pull request Aug 11, 2026
The Snyk Code PR scan flags findProgramOnPath's PATH loop with a LOW
path-traversal finding: env data (PATH) flows into ::open. The open was
only anchoring fstatat/faccessat against each PATH directory; the check
can be expressed directly against the joined candidate path with
::stat + ::faccessat(AT_FDCWD, ...), matching the path-qualified branch
above. stat/access do not read file contents, so the taint path to a
file-read sink is gone -- verified with a local 'snyk code test' on the
same changed-file set the Jenkins stage scans (1 issue -> 0).

The finding only fired on this PR because the diff-scoped scan finally
saw both the taint source (PosixEnvironment.cpp, core::system::getenv)
and the sink file together; the flagged code itself is from #9620.

Behavior notes: empty PATH entries are now skipped explicitly (open("")
failed naturally before; completeChildPath would otherwise resolve them
against the working directory), and symlinks are still followed. The
FindProgram* gtests pass unchanged.
kevinushey added a commit that referenced this pull request Aug 11, 2026
* harden session startup against silent background-thread crashes

Investigation of the PR-18509 c++-unit-tests segfault (rsession died
~250ms into startup with no diagnostics) identified why such crashes
are silent and several startup hazards that fit the failure signature.
Addresses #10756.

Why crashes were silent: safeLaunchThread and core::thread::run block
ALL signals on every background thread. Synchronous fault signals are
always delivered to the faulting thread, so blocking them cannot route
them elsewhere -- the kernel just bypasses any installed crash handler
(libSegFault included) and kills the process with no output.

Changes:

- SignalBlocker::blockAll no longer blocks SIGSEGV/SIGBUS/SIGILL/
  SIGFPE, so crashes on background threads produce crash reports.

- core::system::{getenv,setenv,unsetenv,environment} on POSIX now
  serialize on a pthread mutex: glibc setenv can reallocate the environ
  array while a concurrent getenv walks it unlocked (the crash class
  already documented for getaddrinfo/LOCALDOMAIN, rstudio-pro#4628).
  The mutex participates in pthread_atfork because forked children read
  the environment before exec (launchChildProcess reads SHELL).

- the desktop parent-termination monitor thread no longer reads
  RS_PPM_FD_* from the environment on the freshly launched (fully
  signal-masked) thread; the fds are read on the main thread and passed
  in. This getenv raced the setenv(RS_RPOSTBACK_PATH) executed
  immediately after the thread spawn -- the best-fitting candidate for
  the observed crash: desktop-mode-only, silent, and scheduling-
  dependent. Windows/macOS variants unchanged.

- initializeLogConfigReload only starts one SIGHUP reload thread even
  though desktop mode initializes logging twice.

Tests: new core gtests assert the launched-thread signal mask (fault
signals unblocked, async signals blocked) and the fd-based
waitForParentTermination semantics. 487 core + 416 rsession tests
pass.

* extend environment locking to all raw accessors, cross-platform

Survey of remaining raw ::getenv / ::setenv use found several sites that
bypassed the new lock, including one that shared_core cannot reach from
core (dependency direction). Promote the lock to a public cross-platform
primitive and cover them:

- new shared_core/system/EnvironmentLock.{hpp,cpp}: POSIX uses the
  pthread mutex + pthread_atfork integration (moved from core's
  PosixEnvironment.cpp); Windows uses a statically-initialized SRWLOCK.
  Windows' Get/SetEnvironmentVariable already serialize internally, but
  the lock gives uniform semantics so call sites need not special-case
  platforms. The lock is not recursive: it is taken at the lowest level
  that touches the environment, exactly once (Win32Environment::getenv
  delegates to detail::getenv and so does not lock).

- shared_core posix::getEnvironmentVariable now locks; it backs
  User::getUserHomePath's HOME reads, which are reachable from
  background threads.

- EnvironmentScope captured the char* returned by ::getenv and
  dereferenced it in its destructor, after intervening setenvs may have
  reallocated environ -- a dangling pointer independent of threading.
  It now copies the previous value under the lock (preserving the
  set-but-empty vs unset distinction).

- PosixParentProcessMonitor's getFdEnv/setFdEnv lock; also fix setenv's
  third argument, which was passing a string length where the API takes
  an overwrite flag (worked only by accident).

- SessionConsoleProcess's two ::getenv("ENV") reads lock, keeping the
  raw call for the set-but-empty vs unset distinction.

Left alone deliberately: r::util::getenv (R's Sys.getenv, main-thread
confined; R reads the environment internally either way), the
single-threaded rserver-url-ports binary and ServerSetupDb setup path,
test bodies, and libc-internal readers (getaddrinfo/LOCALDOMAIN), which
no lock of ours can cover.

Tests: EnvironmentScope restore/unset semantics (including an
environ-reshuffle case that dangled with the old char* member) and a
two-thread getenv/setenv hammer; a locking regression shows up there as
a watchdog-reported deadlock. 490 core + 416 rsession tests pass.

* check PATH candidates directly instead of via directory fds

The Snyk Code PR scan flags findProgramOnPath's PATH loop with a LOW
path-traversal finding: env data (PATH) flows into ::open. The open was
only anchoring fstatat/faccessat against each PATH directory; the check
can be expressed directly against the joined candidate path with
::stat + ::faccessat(AT_FDCWD, ...), matching the path-qualified branch
above. stat/access do not read file contents, so the taint path to a
file-read sink is gone -- verified with a local 'snyk code test' on the
same changed-file set the Jenkins stage scans (1 issue -> 0).

The finding only fired on this PR because the diff-scoped scan finally
saw both the taint source (PosixEnvironment.cpp, core::system::getenv)
and the sink file together; the flagged code itself is from #9620.

Behavior notes: empty PATH entries are now skipped explicitly (open("")
failed naturally before; completeChildPath would otherwise resolve them
against the working directory), and symlinks are still followed. The
FindProgram* gtests pass unchanged.

* clarify that unlocked third-party environment writes remain unserialized
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