Who can delete a file?
I created a file, did chmod 000 to it and then changed the owner and group to root:root. I was still able to delete the file as the original creator of it (not root).
Who has permissions to delete a file?
The permissions of the containing directory determine the ability to rename and delete files.
Specifically, to delete/rename a file, a user needs to have write and execute (i.e. traversal) permissions on the containing directory, and the file in question must not be immutable. (Under these circumstances, a non-privileged user can even delete files owned by root.)
Restricted Deletion:
It is possible to restrict deletion of files to only the owner of the files (and privileged users), by setting the 'sticky bit' (also known as the 'restricted deletion flag') on the containing directory using: chmod +t directory
. A directory with the sticky bit set, displays a 't' in the last position (e.g. drwxr-xr-t
) - this can also be set in 'octal' form by prefixing the 3 digit octal code with a '1' (e.g. chmod 1755 directory
). (Linux ignores the sticky bit on files - although some other operating systems do assign meaning to it.)
Read Permissions:
You should note that the read permission on the containing directory is not required. Without it, you will still be able to delete the file, if you know its name, although you will not be able to 'read' the contents of the directory (e.g. without read permissions you cannot run ls
).
Immutable Files:
As a side point, by making a file immutable (i.e. chattr +i
) neither the owner nor other users (including privileged users) will be able to delete (or rename, link to, or modify) the file, even if they have write permissions on the directory (only the superuser can remove this).
The owner of the folder where the file resides will, if they have write permissions on the folder, be able to delete the file even if it's mask is 000 or the file is owned by another user. If you really want to create a file that no one can touch/delete you should look into the command chattr
and its immutable flag.
From the documentation:
A file with the i attribute cannot be modified: it cannot be deleted or renamed, no link can be created to this file and no data can be written to the file. Only the superuser or a process possessing the
CAP_LINUX_IMMUTABLE
capability can set or clear this attribute.