From 74da58248840b67bc0e933e295ab53094a753c0e Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Fri, 20 Nov 2026 17:13:09 +0100 Subject: [PATCH] tmpfiles: set the owner before the mode An entry that sets both setuid or setgid and another owner lost the bit again: f /usr/libexec/helper 4755 app app The mode was set first, and a change of owner drops setuid and setgid from a file. A second run put it back, the owner was right by then. Change the owner first. A mode that is not in the entry is put back the same way. Also, a mode that ~ masks down to 0 is now set, 0 was taken for no mode. Signed-off-by: Joachim Wiberg --- src/tmpfiles.c | 34 +++++++++++++++++++++------------- test/tmpfiles-perm.sh | 13 +++++++++++++ 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/src/tmpfiles.c b/src/tmpfiles.c index 080fa24c..20d8f3fc 100644 --- a/src/tmpfiles.c +++ b/src/tmpfiles.c @@ -377,25 +377,22 @@ static int fd_chmod(int fd, mode_t mode) */ static int perm_set(int fd, const struct perm *p, int created) { - mode_t mode = p->mode; int uid = p->uid, gid = p->gid; + int chowned = 0; struct stat st; + mode_t mode; if (fstat(fd, &st)) return -1; if (S_ISLNK(st.st_mode)) return 0; - if (!created) { - if (p->new_mode) - mode = 0; - if (p->new_uid) - uid = -1; - if (p->new_gid) - gid = -1; + mode = st.st_mode & 07777; + if (p->mode && (created || !p->new_mode)) { + mode = p->mode; /* Keep read, write, and execute only where the path has it for someone */ - if (mode && p->mask) { + if (p->mask && !created) { for (mode_t bits = 0111; bits <= 0444; bits <<= 1) { if (!(st.st_mode & bits)) mode &= ~bits; @@ -404,11 +401,22 @@ static int perm_set(int fd, const struct perm *p, int created) mode &= ~07000; } } + if (!created) { + if (p->new_uid) + uid = -1; + if (p->new_gid) + gid = -1; + } - if (mode && (st.st_mode & 07777) != mode && fd_chmod(fd, mode)) - return -1; - if ((uid != -1 && st.st_uid != (uid_t)uid) || (gid != -1 && st.st_gid != (gid_t)gid)) - return fchownat(fd, "", uid, gid, AT_EMPTY_PATH); + if ((uid != -1 && st.st_uid != (uid_t)uid) || (gid != -1 && st.st_gid != (gid_t)gid)) { + if (fchownat(fd, "", uid, gid, AT_EMPTY_PATH)) + return -1; + chowned = 1; + } + + /* A change of owner drops setuid and setgid, so the mode goes last */ + if ((st.st_mode & 07777) != mode || (chowned && (mode & 06000))) + return fd_chmod(fd, mode); return 0; } diff --git a/test/tmpfiles-perm.sh b/test/tmpfiles-perm.sh index 85f8c9b6..11a911c4 100755 --- a/test/tmpfiles-perm.sh +++ b/test/tmpfiles-perm.sh @@ -90,3 +90,16 @@ sep say 'A p entry leaves a path that is not a fifo alone' run "echo 'p $DIR/file 0644 root root' > $CONF; /libexec/finit/tmpfiles --create $CONF" assert "Not a fifo" "$(texec stat -c '%a %U:%G' $DIR/file)" = "600 sys:bin" + +sep +say 'Setuid survives a change of owner, and ~ can take every bit' +run "touch $DIR/suid $DIR/none; chmod 4755 $DIR/suid; chmod 111 $DIR/none" +run "cat > $CONF" <