Linux – Why was I able to delete a file owned by root in the home directory without being root

linuxpermissionsSecurity

So I was doing some maintenance on my server earlier today and noticed I was able to delete a file owned by root in my home directory.

I was able to reproduce a sample:

[cbennett@nova ~/temp]$ ls -al
total 8
drwxrwxr-x.  2 cbennett cbennett 4096 Oct  5 20:59 .
drwxr-xr-x. 22 cbennett cbennett 4096 Oct  5 20:58 ..
-rw-rw-r--.  1 cbennett cbennett    0 Oct  5 20:58 my-own-file
[cbennett@nova ~/temp]$ sudo touch file-owned-by-root
[cbennett@nova ~/temp]$ ls -al
total 8
drwxrwxr-x.  2 cbennett cbennett 4096 Oct  5 21:00 .
drwxr-xr-x. 22 cbennett cbennett 4096 Oct  5 20:58 ..
-rw-r--r--.  1 root     root        0 Oct  5 21:00 file-owned-by-root
-rw-rw-r--.  1 cbennett cbennett    0 Oct  5 20:58 my-own-file
[cbennett@nova ~/temp]$ rm file-owned-by-root
rm: remove write-protected regular empty file ‘file-owned-by-root’? y
[cbennett@nova ~/temp]$ ls -al
total 8
drwxrwxr-x.  2 cbennett cbennett 4096 Oct  5 21:00 .
drwxr-xr-x. 22 cbennett cbennett 4096 Oct  5 20:58 ..
-rw-rw-r--.  1 cbennett cbennett    0 Oct  5 20:58 my-own-file
[cbennett@nova ~/temp]$

My question is how was I able to delete a file that's owned by root and has permissions -rw-r--r--, while I'm not root?

Best Answer

The permissions, content and all attributes are part of the inode. The name is in the directory entry. The permissions are not inherited recursively (except when you use default in Posix ACLs).

When you delete a file, internally you just remove a hard link from the directory entry to the inode. When all hardlinks are removed and the inode is not in use, the filesystem will reclaim the space. You need only write permission on the folder no matter which permissions are set on the file (with the exception of immutable ext permission). Same for an empty folder.

When you delete a folder that is not empty you need write permission on the folder you are deleting and its parent.