Why is rm allowed to delete a file under ownership of a different user?
The reason why this is permitted is related to what removing a file actually does. Conceptually, rm
's job is to remove a name entry from a directory. The fact that the file may then become unreachable if that was the file's only name and that the inode and space occupied by the file can therefore be recovered at that point is almost incidental. The name of the system call that the rm
command invokes, which is unlink
, is even suggestive of this fact.
And, removing a name entry from a directory is fundamentally an operation on that directory, so that directory is the thing that you need to have permission to write.
The following scenario may make it feel more comfortable? Suppose there are directories:
/home/me # owned and writable only by me
/home/you # owned and writable only by you
And there is a file which is owned by me and which has two hard links:
/home/me/myfile
/home/you/myfile
Never mind how that hard link /home/you/myfile
got there in the first place. Maybe root
put it there.
The idea of this example is that you should be allowed to remove the hard link /home/you/myfile
. After all, it's cluttering up your directory. You should be able to control what does and doesn't exist inside /home/you
. And when you do remove /home/you/myfile
, notice that you haven't actually deleted the file. You've only removed one link to it.
Note that if the sticky bit is set on the directory containing a file (shows up as t
in ls
), then you do need to be the owner of the file in order to be allowed to delete it (unless you own the directory). The sticky bit is usually set on /tmp
.
In order to unlink a file, you just need to be able to write to the directory the file is in.
If you don't like this, you could set the "sticky" bit via chmod +t dir
if you are on a halfway recent OS (this feature was introduced around 1986 in SunOS).
If you like to be more fine grained, you need a filesystem with a modern ACL implementaion like ZFS. The standard NFSv4 ACLs based on NTFS include support for file specific delete permissions per user and a "delete_child" permission for directories.