basic: allow copy_rights() to work without mounted /proc

This will be used in sysusers later on.
This commit is contained in:
Zbigniew Jędrzejewski-Szmek
2021-05-24 21:41:22 +02:00
parent 335f6ab4f1
commit 0520564dcf
4 changed files with 32 additions and 10 deletions
+22 -6
View File
@@ -227,7 +227,7 @@ int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
return fchmod_and_chown(fd, mode, uid, gid);
}
int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {
bool do_chown, do_chmod;
struct stat st;
int r;
@@ -238,7 +238,11 @@ int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
* unaffected if the uid/gid is changed, i.e. it undoes implicit suid/sgid dropping the kernel does
* on chown().
*
* This call is happy with O_PATH fds. */
* This call is happy with O_PATH fds.
*
* If path is given, allow a fallback path which does not use /proc/self/fd/. On any normal system
* /proc will be mounted, but in certain improperly assembled environments it might not be. This is
* less secure (potential TOCTOU), so should only be used after consideration. */
if (fstat(fd, &st) < 0)
return -errno;
@@ -263,8 +267,14 @@ int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
if (((minimal ^ st.st_mode) & 07777) != 0) {
r = fchmod_opath(fd, minimal & 07777);
if (r < 0)
return r;
if (r < 0) {
if (!path || r != -ENOSYS)
return r;
/* Fallback path which doesn't use /proc/self/fd/. */
if (chmod(path, minimal & 07777) < 0)
return -errno;
}
}
}
@@ -274,8 +284,14 @@ int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
if (do_chmod) {
r = fchmod_opath(fd, mode & 07777);
if (r < 0)
return r;
if (r < 0) {
if (!path || r != -ENOSYS)
return r;
/* Fallback path which doesn't use /proc/self/fd/. */
if (chmod(path, mode & 07777) < 0)
return -errno;
}
}
return do_chown || do_chmod;