GHSA-PQXF-VF75-QFXJ
chmod: `--reference` combined with `-R` dereferences symlinks encountered during recursion, allowing arbitrary file permission modification (local privilege escalation)
CVSS:3.1/AV:L/AC:L/PR:L/UI:R/S:C/C:H/I:H/A:H
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Remediación | Parche 0.11.0 | coreutils · -4 d desde divulgación | |
| Divulgación | Publicada | GHSA-PQXF-VF75-QFXJ divulgada · CVSS 8.2 (GitHub) | |
| Divulgación | Modificada | Última actualización del registro | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
## Summary
In uutils/coreutils, `chmod`'s internal permission-application routine `Chmoder::chmod_file_internal()` (src/uu/chmod/src/chmod.rs:743-802) contains an asymmetric branch. When the mode is supplied via `--reference=RFILE` (populating `self.fmode`), control flow takes the `if let Some(mode) = self.fmode` branch at line 773 and calls `change_file()` directly. The symlink guard `if file.is_symlink() && !dereference` only exists inside the sibling `else` branch at line 777, so the `--reference` path never evaluates it. `change_file()` at line 808 applies the mode using `fs::set_permissions()`, which is backed by `chmod(2)` and therefore follows symbolic links to their target.
The recursive traversal helper `handle_symlink_during_safe_recursion()` explicitly calls `chmod_file_internal(path, false)` for the default `TraverseSymlinks::First` mode and for `TraverseSymlinks::None` (lines 692-696), with a comment stating that symlinks met during recursion must not be dereferenced. That intent is silently defeated for `--reference`. The result is a behavioural split within the same utility: `chmod -R 755 dir` correctly leaves in-tree symlinks untouched, while `chmod -R --reference=RFILE dir` rewrites the permissions of whatever those symlinks point at. A local unprivileged attacker holding write access to any subdirectory of a tree that a privileged user recursively chmods can plant a symlink and redirect the privileged permission change to an arbitrary file such as `/etc/shadow` or a root-owned binary, yielding local privilege escalation.
## Details
Entry point and configuration
`uumain()` in src/uu/chmod/src/chmod.rs parses `--reference` at lines 128-136. On success, `self.fmode` is set to `Some(meta.mode() & 0o7777)` — the mode bits of the reference file — and `self.cmode` is set to `None`. At lines 165-166, `uucore::perms::configure_symlink_and_recursion(&matches, TraverseSymlinks::First)` returns the tuple `(recursive, dereference, traverse_symlinks)`. With only `-R` supplied (no `-H`/`-L`/`-P`), the default `TraverseSymlinks::First` is preserved and `dereference` resolves to `true` (src/uucore/src/lib/features/perms.rs:869-897).
Reaching the recursion
In `Chmoder::chmod()` (line 370 onward), the command-line operand is checked at line 404 with `!self.dereference && file.is_symlink()`. Because the operand named on the command line is a real directory rather than a symlink, this early-skip does not fire, and execution proceeds to `walk_dir_with_context()` at lines 413-417, which opens the directory with `DirFd::open()` and calls `safe_traverse_dir()`.
Trust boundary crossing
`safe_traverse_dir()` (lines 584-608) enumerates directory entries via `dir_fd.read_dir()`. Attacker-controlled entries in any writable subdirectory appear here. `should_follow_symlink` is computed at line 582 as `self.traverse_symlinks == TraverseSymlinks::All`, which is `false` under the default `First` mode. When `entry_path.is_symlink()` is true at line 600, the entry is dispatched to `handle_symlink_during_safe_recursion()`.
At lines 692-696 the `TraverseSymlinks::First | TraverseSymlinks::None` arm calls `self.chmod_file_internal(path, false)`. The literal `false` is the `dereference` argument, and the in-code comment states the intent plainly: symlinks encountered during recursion must not be followed "even if dereference is normally true".
Root cause — the missing guard
Inside `chmod_file_internal()` the flow reaches lines 772-789. Because `self.fmode` is `Some(...)` under `--reference`, the `if let Some(mode) = self.fmode` arm at line 773 executes `self.change_file(fperm, mode, file)?` immediately. The `dereference` parameter that was carefully threaded through as `false` is never read on this path. The protective check at line 777 (`file.is_symlink() && !dereference`) lives only in the `else` arm and is therefore unreachable whenever `--reference` is in effect.
Dangerous sink
`change_file()` at line 808 performs `fs::set_permissions(file, fs::Permissions::from_mode(mode))`. Rust's `set_permissions` is implemented over `chmod(2)`, not `lchmod`/`fchmodat(AT_SYMLINK_NOFOLLOW)`, so the kernel resolves the symlink and applies the mode to the link target outside the intended directory tree.
Notably, the codebase already contains the correct primitive but does not use it on this path: `Chmoder::safe_chmod_file()` (lines 701-727) calls `dir_fd.chmod_at(entry_name, new_mode, symlink_behavior)`, and `DirFd::chmod_at()` in src/uucore/src/lib/features/safe_traversal.rs:292-413 implements a three-tier no-follow strategy (`fchmodat2` syscall 452, `fchmodat` with `AT_SYMLINK_NOFOLLOW`, and an `O_PATH|O_NOFOLLOW` + `/proc/self/fd` fallback). The `--reference` recursion path bypasses this hardened helper entirely.
Behavioural contrast confirming the defect
Running `chmod -R 755 dir` takes the `else` arm, hits the line 777 guard, and leaves in-tree symlinks and their targets unmodified. Running `chmod -R --reference=RFILE dir` over the identical tree takes the line 773 arm and rewrites the link targets. This divergence within one utility demonstrates an implementation defect rather than intentional design, and it contradicts the established GNU coreutils semantics where recursive chmod defaults to `-P` (do not traverse or dereference symbolic links).
Core vulnerable code path:
// src/uu/chmod/src/chmod.rs:128-136
let fmode = match matches.get_one::<OsString>(options::REFERENCE) {
Some(fref) => match fs::metadata(fref) {
Ok(meta) => Some(meta.mode() & 0o7777),
Err(_) => {
return Err(ChmodError::CannotStat(fref.into()).into());
}
},
None => None,
};The `--reference=RFILE` option populates `self.fmode` with `Some(...)`. This single value is what later steers control flow into the unguarded branch at line 773. When `--reference` is absent, `fmode` is `None` and the safe `else` branch is taken instead.
// src/uu/chmod/src/chmod.rs:692-696
TraverseSymlinks::First | TraverseSymlinks::None => {
// Don't follow symlinks encountered during recursion
// For these symlinks, don't dereference them even if dereference is normally true
self.chmod_file_internal(path, false)
}The recursive traversal explicitly requests no-dereference behaviour for symlinks found inside the tree by passing `dereference = false`. This is the security intent that the vulnerable branch silently discards; `TraverseSymlinks::First` is the default mode when only `-R` is given.
// src/uu/chmod/src/chmod.rs:772-789
// Determine how to apply the permissions
if let Some(mode) = self.fmode {
self.change_file(fperm, mode, file)?;
} else {
// Special handling for symlinks when not dereferencing
if file.is_symlink() && !dereference {
// TODO: On most Unix systems, symlink permissions are ignored by the kernel,
// so changing them has no effect. We skip this operation for compatibility.
// Note that "chmod without dereferencing" effectively does nothing on symlinks.
if self.verbose {
println!(
"neither symbolic link {} nor referent has been changed",
file.quote()
);
}
} else {
self.change_file(fperm, new_mode, file)?;
}The core defect. The `--reference` path (line 773) calls `change_file()` directly without ever evaluating the `dereference` argument. The symlink protection at line 777 is confined to the `else` arm and is therefore unreachable under `--reference`, so the no-dereference contract established at line 695 is broken.
// src/uu/chmod/src/chmod.rs:804-812
fn change_file(&self, fperm: u32, mode: u32, file: &Path) -> Result<(), i32> {
// Always issue the chmod(2) call, even when the bits are unchanged: the
// syscall can still fail (e.g. lacking permission on the file) and that
// failure must be reported, matching GNU.
if let Err(err) = fs::set_permissions(file, fs::Permissions::from_mode(mode)) {
if !self.quiet {
show_error!("{}", ChmodError::ChangingPermissions(file.into(), err));
}
if self.verbose {The dangerous sink. `fs::set_permissions` is backed by `chmod(2)`, which resolves symbolic links and applies the mode to the link target. Because `file` here is the attacker-planted symlink path, the privileged process modifies a file outside the intended tree. The project's own no-follow helper `DirFd::chmod_at(..., SymlinkBehavior::NoFollow)` is not used on this path.
## POC
Preconditions
- A Unix/Linux system where `chmod` is provided by uutils/coreutils (either the multi-call `coreutils` binary or the standalone `uu_chmod`).
- A privileged user (root, or any user with write access to the eventual target file) runs `chmod -R --reference=RFILE <dir>` over a directory tree. This is a common permission-normalisation step in packaging scripts, container builds, and deployment automation.
- The attacker has write access to at least one subdirectory inside that tree (for example a shared upload directory or a build-artifact directory).
- The attacker can create symbolic links — available to any unprivileged user by default.
No race window is required: the symlink is planted statically ahead of time.
Step 1 — Prepare the environment (as the system owner, for reproduction purposes)
mkdir -p /srv/shared/pub
printf 'root:$6$secret:1::::::\n' > /srv/sensitive
chmod 600 /srv/sensitive
touch /tmp/ref
chmod 4777 /tmp/ref
Expected: `/srv/sensitive` is mode 0600; the reference file `/tmp/ref` is mode 4777 (setuid plus world rwx).
Step 2 — Attacker plants the symlink (unprivileged user with write access to /srv/shared/pub)
ln -s /srv/sensitive /srv/shared/pub/evil
ls -l /srv/shared/pub/evil
Expected: `lrwxrwxrwx ... evil -> /srv/sensitive`. No privileges are required to create the link.
Step 3 — Control group, proving the guard works on the non-reference path
chmod -R 755 /srv/shared
stat -c '%a %n' /srv/sensitive
Expected: `600 /srv/sensitive`. The mode is unchanged, confirming that in ordinary numeric/symbolic mode the guard at chmod.rs:777 correctly prevents dereferencing.
Step 4 — Trigger the vulnerability
chmod -R --reference=/tmp/ref /srv/shared
stat -c '%a %n' /srv/sensitive
Expected: `4777 /srv/sensitive`. The symlink target — a file entirely outside `/srv/shared` — has had its permissions rewritten to the reference file's mode, while the symlink itself is untouched. The contrast with the `600` observed in Step 3 isolates the defect to the `--reference` branch.
Step 5 — Demonstrate the privilege-escalation consequence
id -u
cat /srv/sensitive
echo 'attacker:x:0:0::/root:/bin/sh' >> /srv/sensitive
Expected: a non-root user can now read and write a file that was originally mode 0600. If the chosen target is a root-owned binary rather than a data file, the same primitive sets the setuid bit and yields direct root code execution.
Notes on verification status
The code path was closed end-to-end by direct source reading, with every cited line number taken from the actual file contents. Runtime execution of the PoC was not performed because no Rust toolchain (`cargo`/`rustc`) was available in the audit environment. The Step 3 versus Step 4 comparison is the decisive observable and should be run in an environment with a Rust toolchain to move this from source-verified to runtime-confirmed.
## Impact
This is a local privilege escalation primitive. An unprivileged local attacker who can write to any subdirectory of a tree that a privileged process recursively chmods with `--reference` can redirect that permission change to an arbitrary file reachable by symbolic link, entirely outside the intended scope.
Concrete consequences depend on the mode bits of the reference file:
- Confidentiality: making `/etc/shadow`, service private keys, credential files, or database configuration world-readable leads to direct credential theft.
- Integrity: making `/etc/passwd`, `/etc/sudoers.d/*` fragments, cron entries, or systemd unit files world-writable allows the attacker to inject accounts, sudo rules, or scheduled commands.
- Privilege boundary: if the reference file carries setuid or setgid bits (as `4777` does), applying that mode to an existing root-owned executable grants immediate root code execution.
- Availability: stripping execute or read bits from critical system binaries and configuration can render services or the host unusable.
The scope is changed because the vulnerable component (a chmod invocation intended to affect one directory tree) acts on resources managed by a different security authority. `chmod -R --reference=` is a routine idiom in packaging scripts, container image builds, CI artifact publishing, and deployment automation — precisely the contexts that run with elevated privileges over directories containing untrusted, user-writable content. uutils/coreutils is being adopted by multiple Linux distributions as a drop-in replacement for GNU coreutils, so the practical exposure is significant, and the behaviour diverges from GNU coreutils, meaning operators inherit the risk without any change to their scripts.
## Remediation
Primary fix — hoist the symlink check out of the branch
Move the symlink determination so that both the `--reference` (`fmode`) path and the symbolic/numeric mode path share the same protection. In `chmod_file_internal()` (src/uu/chmod/src/chmod.rs:772-789), evaluate the guard first and select the mode afterwards, conceptually:
- If `file.is_symlink() && !dereference`, emit the "neither symbolic link ... nor referent has been changed" message when verbose and return `Ok(())` — before any branch on `self.fmode`.
- Only then choose between `self.fmode` and the computed `new_mode` and call `change_file()`.
Preferred fix — use the existing no-follow primitive on the recursion path
The repository already provides a hardened helper. Route recursive entries through `Chmoder::safe_chmod_file()` (src/uu/chmod/src/chmod.rs:701-727), which calls `dir_fd.chmod_at(entry_name, new_mode, SymlinkBehavior::NoFollow)`. `DirFd::chmod_at()` (src/uucore/src/lib/features/safe_traversal.rs:292-413) implements `fchmodat2`, `fchmodat` with `AT_SYMLINK_NOFOLLOW`, and an `O_PATH|O_NOFOLLOW` plus `/proc/self/fd` fallback. This eliminates symlink following at the syscall level and additionally closes the TOCTOU window between the `fstatat` and the `chmod`. Note that `safe_chmod_file()` currently derives its mode via `calculate_new_mode()`, so it must be extended to honour `self.fmode` correctly before it can serve the `--reference` path.
Defence in depth
- Audit every other call site of `fs::set_permissions()` in the recursive utilities for the same pattern; path-based `chmod(2)` should not be used on entries reached during a traversal where a directory file descriptor is already held.
- Align behaviour with GNU coreutils: recursive `chmod` defaults to `-P` and must not traverse or dereference symbolic links unless `-L` or `-H` is explicitly requested.
Regression tests
Add coverage for the combination that is currently untested. The existing tests `test_chmod_no_dereference_symlink` (tests/by-util/test_chmod.rs, from line 918) and `test_chmod_reference_file` (from line 368) each exercise only one dimension, which is why this defect escaped detection. A new test should create a directory containing a symlink to an out-of-tree file, run `chmod -R --reference=<ref>` on that directory, and assert that the link target's mode is unchanged. Mirror the same assertion for `-L`, `-H`, and `-P` to lock in the documented traversal semantics.
Fix
Fixed by commit db38d1eee ("chmod: don't follow in-tree symlinks with -R --reference"),
pushed directly to `main` on 2026-08-11 together with `0b105f72c`. (An earlier version of
this advisory cited a pull request number that does not exist; these commits landed on `main`
without a PR.) The 0.10.0 tag
predates the fix (tagged 2026-08-05), so 0.10.0 is affected. The fix ships in 0.11.0, released 2026-08-31. The symlink guard is now
evaluated before the mode source is selected, so `--reference` follows the same no-dereference
contract as numeric/symbolic modes, and regression tests cover `-R --reference` with `-P`/`-H`/`-L`.
The same defect was reported independently as GHSA-cwq2-mw2x-h4jw; both reporters are credited here.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
crates.iocoreutils |
Corregida | 0.11.0 | -4 d | 0.12.0 no afectada |
0.11.0Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/uutils/coreutils/security/advisories/GHSA-pqxf-vf75-qfxjLas referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
