Ubuntu – When does chmod fail

access-controlchmodpermissionsUbuntu

Under what circumstances will chmod fail?

I looked at the man page but it only specifies usage and doesn't go into details about what circumstances it won't work in.

I'd assume chmod will work if:

  • you're root
  • you own the target file (and are setting a mundane mode bit i.e. not sticky bit, others)

Can users use chmod to change permissions on a file they have group access for? Is it related to read/write access?

Best Answer

Only the owner of the file, or the root user, may change a file's permissions. The current permissions on the file or on its parent directory are irrelevant¹. This is specified in POSIX:

The application shall ensure that the effective user ID of the process matches the owner of the file or the process has appropriate privileges in order to do this.

On most unices, “appropriate privileges” means running as root. If these conditions are not met, chmod usually fails with EPERM, though other behaviors such as aborting the program due to a security violation are permitted.

In addition, some unix variants have system-specific ways of authorizing or forbidding chmod. For example, Linux has a capability (CAP_FOWNER) that allows processes to change a file's permissions and other metadata regardless of its owner.

There are other reasons chmod might fail even though the file exists, is accessible and has the appropriate owner. Common ones include a read-only filesystem or a filesystem that does not support permissions such as FAT. Less common ones include system-specific restrictions such as the immutable attribute on Linux's ext2 filesystem and successors.

¹ Except insofar as he process running chmod must be able to access the file, so it must have execute permission on the directory containing the file and any other directory that it traverses to do so.