Skip to content

Commit 3fcc055

Browse files
prestisttravier
authored andcommitted
internal/exec/util/file: Set ownership first, then mode
From https://man7.org/linux/man-pages/man2/lchown.2.html: > When the owner or group of an executable file is changed by an > unprivileged user, the S_ISUID and S_ISGID mode bits are cleared. > POSIX does not specify whether this also should happen when root > does the chown(); the Linux behavior depends on the kernel version, > and since Linux 2.2.13, root is treated like other users. Fixes: #2042
1 parent c8edf88 commit 3fcc055

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

internal/exec/util/file.go

+14-6
Original file line numberDiff line numberDiff line change
@@ -151,20 +151,28 @@ func (u Util) WriteLink(s types.Link) error {
151151
}
152152

153153
func (u Util) SetPermissions(mode *int, node types.Node) error {
154-
if mode != nil {
155-
if err := os.Chmod(node.Path, ToFileMode(*mode)); err != nil {
156-
return fmt.Errorf("failed to change mode of %s: %v", node.Path, err)
157-
}
158-
}
159-
154+
// Set ownership and then permissions.
155+
// From https://man7.org/linux/man-pages/man2/lchown.2.html:
156+
// "When the owner or group of an executable file is changed by an
157+
// unprivileged user, the S_ISUID and S_ISGID mode bits are cleared. POSIX
158+
// does not specify whether this also should happen when root does the
159+
// chown(); the Linux behavior depends on the kernel version, and since
160+
// Linux 2.2.13, root is treated like other users."
160161
defaultUid, defaultGid, _ := getFileOwnerAndMode(node.Path)
161162
uid, gid, err := u.ResolveNodeUidAndGid(node, defaultUid, defaultGid)
162163
if err != nil {
163164
return fmt.Errorf("failed to determine correct uid and gid for %s: %v", node.Path, err)
164165
}
166+
165167
if err := os.Lchown(node.Path, uid, gid); err != nil {
166168
return fmt.Errorf("failed to change ownership of %s: %v", node.Path, err)
167169
}
170+
171+
if mode != nil {
172+
if err := os.Chmod(node.Path, ToFileMode(*mode)); err != nil {
173+
return fmt.Errorf("failed to change mode of %s: %v", node.Path, err)
174+
}
175+
}
168176
return nil
169177
}
170178

0 commit comments

Comments
 (0)