Search code examples
file-permissions

why vim can overwrite other user file under its home directory


For example, root touch a new file under a common user's(name it bob) home directory:

/home/bob $ ls -alh a.txt
-rw-r--r-- 1 root root 0 Jul 16 17:45 a.txt

Now user bob open it with vim, and it should be readonly.

I tried to force overwrite it with :w!, and it was saved and the owner:group changed to bob:

/home/bob $ ls -alh a.txt
-rw-r--r-- 1 bob bob 4 Jul 16 17:47 a.txt

IMO, I think it can't be saved with permission denied, but it could, and the owner:group also changed.

And this can only under bob's home directory, if under outer directory, such as /tmp or others, it can't be written as I thought.

Can anyone explain this? what processes does :w! actual do? thx.


Solution

  • The file is readable by Bob, so Bob can open it in Vim.

    The directory is writable by Bob, so Bob will be able to unlink (remove) any file therein, and write any new file to it. This is what happens when you use :w!.

    This is not true for the /tmp directory, because it probably has the "sticky" bit set.

    From the OS X sticky(8) manual:

    A directory whose 'sticky bit' is set becomes an append-only directory, or, more accurately, a directory in which the deletion of files is restricted. A file in a sticky directory may only be removed or renamed by a user if the user has write permission for the directory and the user is the owner of the file, the owner of the directory, or the super-user. This feature is usefully applied to directories such as /tmp which must be publicly writable but should deny users the license to arbitrarily delete or rename each others' files.