← Back to Pull requests

stdbuf: keep the preload path out of reach of other users #16817

Open
Socialpranker opened this pull request with 164 lines diff across 6 files
View on GitHub
Socialpranker Socialpranker commented on Nov 24, 2026 10:57 UTC
Author

The embedded libstdbuf is extracted below $TMPDIR and its path is put into LD_PRELOAD. #13622 refuses a : in that path, but two ways around it are left (both came up in #15268):

  • glibc also splits LD_PRELOAD on spaces, so TMPDIR='/x/evil.so /../../tmp' makes the command preload /x/evil.so;

  • whoever owns $TMPDIR can swap the freshly created directory for their own before the command is executed, with no special character in the path.
  • As in #13622, this matters only when TMPDIR crosses a privilege boundary, and only for builds that embed libstdbuf.

    What changes: the directory is created in $TMPDIR only if nobody but root and the current user can rename it or one of its ancestors, otherwise in /tmp. If /tmp does not qualify either, stdbuf exits with an error. The path is canonicalized first, and whitespace is refused next to :.

    I kept a real path instead of memfd because of the problems with child processes found in #15268.

    One behavior change: in a user namespace where / belongs to an unmapped uid, the embedded build now fails instead of running.

    Tested on Linux with glibc. With a process racing to swap the directory, the foreign library was loaded in 25 of 30 runs before the change and in 0 of 30 after.

    The patch was written with AI assistance and tested as described above.

    Diff: 164 lines (+138 / -26) across 6 files Reviewer: oech3 Review duration: 15539m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.41) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.41 · 164 lines diff across 6 files
    0.41
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.305
    Real PR Conversation Timeline
    12 items
    oech3 oech3 commented on code on Nov 24, 2026 12:58 UTC
    Code Review
    src/uu/stdbuf/locales/en-US.ftl:1
    @@ -25,7 +25,7 @@ stdbuf-error-line-buffering-stdin-meaningless = line buffering stdin is meaningl
     stdbuf-error-invalid-mode = invalid mode {$error}
     stdbuf-error-value-too-large = invalid mode '{$value}': Value too large for defined data type
     stdbuf-error-external-libstdbuf-not-found = External libstdbuf not found at configured path: {$path}
    -stdbuf-error-preload-path-separator = libstdbuf path {$path} contains ':', which cannot be represented in {$var}
    -  stdbuf: set TMPDIR to a directory whose path has no ':'
    +stdbuf-error-preload-path-separator = libstdbuf path {$path} contains ':' or whitespace, which cannot be represented in {$var}

    Can we simplify this like libstdbuf path contains insecure letter: *?

    sylvestre sylvestre commented on code on Nov 24, 2026 21:41 UTC
    Code Review
    src/uu/stdbuf/src/stdbuf.rs:1
    @@ -153,6 +153,61 @@ fn set_command_env(command: &mut process::Command, buffer_name: &str, buffer_typ
         }
     }
     
    +/// Whether nobody but root and the owner of `dir` can rename or replace `dir`
    +/// or one of its ancestors. `dir` was just created by us, so its owner is our
    +/// effective user.
    +#[cfg(all(unix, not(feature = "feat_external_libstdbuf")))]
    +fn is_out_of_reach_of_others(dir: &std::path::Path) -> bool {
    +    use std::os::unix::fs::MetadataExt;
    +
    +    let Ok(uid) = dir.metadata().map(|m| m.uid()) else {

    this should be geteuid(), not the owner of dir.
    if the owner of $TMPDIR swaps dir for one of their own before this runs, both uids match and the check passes

    sylvestre sylvestre commented on code on Nov 24, 2026 21:41 UTC
    Code Review
    src/uu/stdbuf/src/stdbuf.rs:1
    @@ -153,6 +153,61 @@ fn set_command_env(command: &mut process::Command, buffer_name: &str, buffer_typ
         }
     }
     
    +/// Whether nobody but root and the owner of `dir` can rename or replace `dir`
    +/// or one of its ancestors. `dir` was just created by us, so its owner is our
    +/// effective user.
    +#[cfg(all(unix, not(feature = "feat_external_libstdbuf")))]
    +fn is_out_of_reach_of_others(dir: &std::path::Path) -> bool {
    +    use std::os::unix::fs::MetadataExt;
    +
    +    let Ok(uid) = dir.metadata().map(|m| m.uid()) else {
    +        return false;
    +    };
    +    dir.ancestors().skip(1).all(|ancestor| {
    +        ancestor.metadata().is_ok_and(|m| {
    +            let writable_by_owner_only = m.mode() & 0o022 == 0;
    +            let sticky = m.mode() & 0o1000 != 0;
    +            (m.uid() == uid || m.uid() == 0) && (writable_by_owner_only || sticky)
    +        })
    +    })
    +}
    +
    +/// Create the directory the embedded libstdbuf is extracted to.
    +///
    +/// The path of that directory ends up in the preload variable of the command,
    +/// so whoever can replace the directory or one of its ancestors chooses the
    +/// code the command loads. `$TMPDIR` can be such a place when it is inherited
    +/// across a privilege boundary, so it is only used when it is out of reach of
    +/// other users, with `/tmp` as the second choice. The path is canonicalized
    +/// first: the loader splits the variable as a string, `..` included.
    +#[cfg(not(feature = "feat_external_libstdbuf"))]
    +fn create_preload_dir() -> std::io::Result<TempDir> {
    +    #[cfg(unix)]
    +    {
    +        let mut builder = tempfile::Builder::new();
    +        builder.permissions(Permissions::from_mode(0o700));
    +        for base in [std::env::temp_dir(), PathBuf::from("/tmp")] {
    +            let Ok(base) = base.canonicalize() else {
    +                continue;
    +            };
    +            let Ok(dir) = builder.tempdir_in(base) else {
    +                continue;
    +            };
    +            if is_out_of_reach_of_others(dir.path()) {
    +                return Ok(dir);
    +            }
    +        }
    +        // Falling back to an unchecked $TMPDIR here would let whoever fills
    +        // /tmp bring the old behavior back.
    +        Err(std::io::Error::new(
    +            std::io::ErrorKind::PermissionDenied,
    +            "other users can replace both $TMPDIR and /tmp",

    please use translate!()

    sylvestre sylvestre commented on code on Nov 24, 2026 21:41 UTC
    Code Review
    src/uu/stdbuf/src/stdbuf.rs:1
    @@ -153,6 +153,61 @@ fn set_command_env(command: &mut process::Command, buffer_name: &str, buffer_typ
         }
     }
     
    +/// Whether nobody but root and the owner of `dir` can rename or replace `dir`
    +/// or one of its ancestors. `dir` was just created by us, so its owner is our
    +/// effective user.
    +#[cfg(all(unix, not(feature = "feat_external_libstdbuf")))]
    +fn is_out_of_reach_of_others(dir: &std::path::Path) -> bool {
    +    use std::os::unix::fs::MetadataExt;
    +
    +    let Ok(uid) = dir.metadata().map(|m| m.uid()) else {
    +        return false;
    +    };
    +    dir.ancestors().skip(1).all(|ancestor| {
    +        ancestor.metadata().is_ok_and(|m| {
    +            let writable_by_owner_only = m.mode() & 0o022 == 0;
    +            let sticky = m.mode() & 0o1000 != 0;
    +            (m.uid() == uid || m.uid() == 0) && (writable_by_owner_only || sticky)
    +        })
    +    })
    +}
    +
    +/// Create the directory the embedded libstdbuf is extracted to.
    +///
    +/// The path of that directory ends up in the preload variable of the command,
    +/// so whoever can replace the directory or one of its ancestors chooses the
    +/// code the command loads. `$TMPDIR` can be such a place when it is inherited
    +/// across a privilege boundary, so it is only used when it is out of reach of
    +/// other users, with `/tmp` as the second choice. The path is canonicalized
    +/// first: the loader splits the variable as a string, `..` included.
    +#[cfg(not(feature = "feat_external_libstdbuf"))]
    +fn create_preload_dir() -> std::io::Result<TempDir> {
    +    #[cfg(unix)]
    +    {
    +        let mut builder = tempfile::Builder::new();
    +        builder.permissions(Permissions::from_mode(0o700));
    +        for base in [std::env::temp_dir(), PathBuf::from("/tmp")] {

    what happens on Android? /data/local/tmp is 0771 and there is no /tmp, so i think stdbuf always fails there now

    sylvestre sylvestre commented on code on Nov 24, 2026 21:41 UTC
    Code Review
    src/uu/stdbuf/src/stdbuf.rs:1
    @@ -153,6 +153,61 @@ fn set_command_env(command: &mut process::Command, buffer_name: &str, buffer_typ
         }
     }
     
    +/// Whether nobody but root and the owner of `dir` can rename or replace `dir`
    +/// or one of its ancestors. `dir` was just created by us, so its owner is our
    +/// effective user.
    +#[cfg(all(unix, not(feature = "feat_external_libstdbuf")))]
    +fn is_out_of_reach_of_others(dir: &std::path::Path) -> bool {
    +    use std::os::unix::fs::MetadataExt;
    +
    +    let Ok(uid) = dir.metadata().map(|m| m.uid()) else {
    +        return false;
    +    };
    +    dir.ancestors().skip(1).all(|ancestor| {
    +        ancestor.metadata().is_ok_and(|m| {
    +            let writable_by_owner_only = m.mode() & 0o022 == 0;
    +            let sticky = m.mode() & 0o1000 != 0;
    +            (m.uid() == uid || m.uid() == 0) && (writable_by_owner_only || sticky)
    +        })
    +    })
    +}
    +
    +/// Create the directory the embedded libstdbuf is extracted to.
    +///
    +/// The path of that directory ends up in the preload variable of the command,

    could you please make this comment shorter? 2 lines should be enough

    xtqqczze xtqqczze commented on Nov 28, 2026 23:34 UTC
    Contributor

    Android / Test builds (API 28, x86_64) (pull_request) failed:

    thread 'test_stdbuf::test_stdbuf_unbuffered_stdout' (6329) panicked at tests/by-util/test_stdbuf.rs:221:10:
    Command was expected to succeed. code: 125
    

    Socialpranker Socialpranker commented on Nov 30, 2026 12:11 UTC
    Author

    Thanks for the review. Addressed in cd34d4fb9:

  • The owners of the directory and of every ancestor are now compared with geteuid(), so a directory swapped in by the owner of $TMPDIR fails the check.

  • Android: you're right, /tmp does not exist and every writable directory sits below /data, which belongs to system, so the check could never pass there. On Android stdbuf now uses $TMPDIR as before this PR (canonicalized, still with the separator check). That is what fixes test_stdbuf_unbuffered_stdout on API 28. I could not run the Android job locally; I type-checked that branch for x86_64-linux-android.

  • The new error goes through translate!() (en-US and fr-FR).

  • Both comments are down to two lines.

  • @oech3: the separator message is now libstdbuf path contains an insecure character: <path>, with the TMPDIR hint kept on the second line.
  • Tested on Linux (glibc 2.41, non-root uid): all 22 test_stdbuf tests pass, and the 11 that run on macOS pass too.

    xtqqczze xtqqczze commented on code on Dec 01, 2026 00:24 UTC
    Code Review
    src/uu/stdbuf/Cargo.toml:1
    @@ -26,6 +26,7 @@ thiserror = { workspace = true }
     uucore = { workspace = true, features = ["parser-size"] }
     
     [target.'cfg(unix)'.dependencies]
    +rustix = { workspace = true, features = ["process"] }

    Alphabetize please

    Socialpranker Socialpranker commented on code on Dec 02, 2026 19:56 UTC
    Code Review
    src/uu/stdbuf/Cargo.toml:1
    @@ -26,6 +26,7 @@ thiserror = { workspace = true }
     uucore = { workspace = true, features = ["parser-size"] }
     
     [target.'cfg(unix)'.dependencies]
    +rustix = { workspace = true, features = ["process"] }

    Done in 65455102c, thanks.

    xtqqczze xtqqczze commented on code on Dec 03, 2026 02:17 UTC
    Code Review
    src/uu/stdbuf/Cargo.toml:1
    @@ -26,6 +26,7 @@ thiserror = { workspace = true }
     uucore = { workspace = true, features = ["parser-size"] }
     
     [target.'cfg(unix)'.dependencies]
    +rustix = { workspace = true, features = ["process"] }

    please squash the fixup

    codspeed[bot] codspeed[bot] commented on Dec 03, 2026 03:51 UTC
    Bot

    <!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

    Merging this PR will improve performance by ×3.5

    <details>
    <summary><b>3 warnings, 1 note</b></summary>

    :warning: 122 benchmarks are dominated by system calls

    > System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

    > Learn more about system calls

    > See affected benchmarks

    :warning: 2 benchmarks with a significant change ran on different hardware

    > Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

    > Learn more about Macro Runners

    > See affected benchmarks

    :warning: 2 benchmarks with a significant change ran in a different software environment

    > Their base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the changes might come from this difference rather than from the code. Open an affected benchmark to see what changed.

    > See affected benchmarks

    :information_source: 1 benchmark has no flamegraph

    > The flamegraph wasn't generated: most of the time was spent in runtime internals, which would leave nothing useful to analyze.

    > See affected benchmarks

    </details>

    ⚡ 2 improved benchmarks
    ✅ 421 untouched benchmarks
    ⏩ 78 skipped benchmarks[^skipped]

    Performance Changes

    | | Mode | Benchmark | BASE | HEAD | Efficiency |
    | --- | ---- | --------- | ------ | ------ | ---------- |
    | ⚡ | Memory | [` socket_addrs_direct[100000] ](https://app.codspeed.io/uutils/coreutils/branches/Socialpranker%3Astdbuf-private-preload-dir?uri=src%2Fuu%2Fhostname%2Fbenches%2Fhostname_bench.rs%3A%3Asocket_addrs_direct%255B100000%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 68 KB | 8.6 KB | ×7.9 |
    | ⚡ | Memory | [
    hostname_ip_lookup[100000] ](https://app.codspeed.io/uutils/coreutils/branches/Socialpranker%3Astdbuf-private-preload-dir?uri=src%2Fuu%2Fhostname%2Fbenches%2Fhostname_bench.rs%3A%3Ahostname_ip_lookup%255B100000%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 160.3 KB | 100.9 KB | +58.88% |

    [!TIP]

    Curious why performance improved? Comment @codspeedbot explain why performance improved` on this PR, or directly use the CodSpeed MCP with your agent.

    ---

    <sub>Comparing <code>Socialpranker:stdbuf-private-preload-dir</code> (6545510) with <code>main</code> (acd07b1)[^unexpected-base]</sub>

    <a href="https://app.codspeed.io/uutils/coreutils/branches/Socialpranker%3Astdbuf-private-preload-dir?utm_source=github&utm_medium=comment-v2&utm_content=button">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
    <img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
    </picture>
    </a>

    [^skipped]: 78 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
    [^unexpected-base]: No successful run was found on <code>main</code> (1129d00) during the generation of this report, so acd07b1 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

    Reviewers
    Assignees
    Socialpranker Socialpranker
    Labels
    risk: low confidence: 90.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 40.9% (MEDIUM) · Higher = larger blast radius
    40.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.6% · Lower = rushed or shallow review
    90.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 3.8% · Safe to merge
    3.8%