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 <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg committed 2026-11-20 18:03:31 +01:00
1 parent 777ecd77c8
commit 74da582488
2 files changed
+34 -13

No files matched your search

+21 -13
View File
@@ -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;
}
+13
View File
@@ -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" <<CONF
f $DIR/suid 4755 bin sys
f $DIR/keep - sys bin
f $DIR/none ~0600
CONF
run "touch $DIR/keep; chmod 2755 $DIR/keep; /libexec/finit/tmpfiles --create $CONF"
assert "Mode given" "$(texec stat -c '%a %U:%G' $DIR/suid)" = "4755 bin:sys"
assert "Mode not given" "$(texec stat -c '%a %U:%G' $DIR/keep)" = "2755 sys:bin"
assert "Masked to 0" "$(texec stat -c '%a' $DIR/none)" = "0"