Who can change the permissions of a file/directory?

Only the owner and root (super user) are allowed to the change the permission of a file or directory. This means that the owner and the super user can set the read (r), write (w) and execute (x) permissions. But changing the ownership (user/group) of files and directories with the commands chown/chgrp is only allowed to root.


For the purpose of normal operation, only root and the owner can chmod. In addition, root can chown and chgrp, and furthermore the owner can chgrp as long as the owner is a member of the target group.

For security purposes, there is another case though: any user with write permission to the directory containing the file can replace the file with a copy, and thus become the owner, gaining the ability to modify the permissions and contents.

Like so:

14:14 mybox:~ mkdir mydir
14:14 mybox:~ cd mydir/
14:14 mybox:mydir echo foo | sudo tee yourfile
foo
14:14 mybox:mydir ls -ld . yourfile 
drwxr-xr-x  3 me    staff  102 Apr 11 14:14 .
-rw-r--r--  1 root  staff    4 Apr 11 14:14 yourfile

We created a directory, and wrote a file as root. Since root owns the file, we cannot write to it, nor can we chmod:

14:15 mybox:mydir echo bar > yourfile 
-bash: yourfile: Permission denied
14:15 mybox:mydir chmod a+x yourfile
chmod: Unable to change file mode on yourfile: Operation not permitted

However, we do have write permission to the directory, so we can replace the file to get ownership:

14:15 mybox:mydir mv yourfile yourfile2
14:15 mybox:mydir cp yourfile2 yourfile
14:15 mybox:mydir ls -ld . yourfile 
drwxr-xr-x  4 me   staff  136 Apr 11 14:15 .
-rw-r--r--  1 me   staff    4 Apr 11 14:15 yourfile

And now that we are the owner, we can of course do what we want with that file:

14:15 mybox:mydir echo bar > yourfile 
14:15 mybox:mydir chmod a+x yourfile
14:16 mybox:mydir cat yourfile
bar

Similarly, any user with write permission to any directory in the full path leading to the file can replace the directory structure from that point on, thus gaining ownership of the file with the given name. The ownership or permissions of the actual original file (which we renamed to "yourfile2") isn't changed, of course.

14:17 mybox:mydir ls -l yourfile2
-rw-r--r--  1 root  staff  4 Apr 11 14:14 yourfile2