0

I created user small, added him to group kek and allowed that group to only read files in user home directory. Then I chowned all files to root:kek. However, small still can delete files in his home directory.

Commands I ran:

useradd -ms /bin/bash small
groupadd kek
usermod -a -G kek small
chown -R root:kek /home/small/*
chmod -R g=r  /home/small/*

Then when I try to remove file:

$ ls -l
total 16
-rw-r--r-- 1 root kek  240 Jun 23 06:17 Dockerfile
-rw-r--r-- 1 root kek   39 Jun 21 09:17 flag.txt
-rw-r--r-- 1 root kek 2336 Jun 22 14:19 server.py
-rw-r--r-- 1 root kek   24 Jun 22 08:16 small.py

$ rm flag.txt

$ ls -l
total 12
-rw-r--r-- 1 root kek  240 Jun 23 06:17 Dockerfile
-rw-r--r-- 1 root kek 2336 Jun 22 14:19 server.py
-rw-r--r-- 1 root kek   24 Jun 22 08:16 small.py

$ whoami
small

Why does this happens?

nikrom3000
  • 277
  • 1
  • 4
  • 14

2 Answers2

5

Whether a file can be deleted or not is not a property of the file but of the directory that the file is located in. A user may not delete a file that is located in a directory that they can't write to.

Files (and subdirectories) are entries in the directory node. To delete a file, one unlinks it from the directory node and therefore one has to have write permissions to the directory to delete a file in it.

  • The write permissions on a file determines whether one is allowed to change the contents of the file.
  • The write permissions on a directory determines whether one is allowed to change the contents of the directory.

Related:

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • Small question: now I created directory `/home/small/server`, put all files there and `chown` and `chmod` the same way as before. Now `small` cannot chdir to that directory even though group `kek` has read permission, why? – nikrom3000 Jun 23 '18 at 06:40
  • Why is execute permission needed? – nikrom3000 Jun 23 '18 at 06:41
  • 1
    @nikrom3000 [Execute vs Read bit. How do directory permissions in Linux work?](https://unix.stackexchange.com/questions/21251/execute-vs-read-bit-how-do-directory-permissions-in-linux-work) – PesaThe Jun 23 '18 at 06:46
  • @nikrom3000 To `cd` into a directory, the user must have execute permissions on it. Read permissions only gives you the ability to list files. – Kusalananda Jun 23 '18 at 07:06
1

On Unix you do not delete a file, you remove it from a directory listing. When a file no-longer has any directory listings (it can have many), and is no-longer open by a process, then it will be deleted.

If you have write permission on a directory, then you can remove a files directory listing.

What to do about it

  • Option 1 Remove write permission from the directory.
  • Option 2 Add the sticky bit to the directory (chmod +t «directory-name»). Make it so that only the owner and root (actually has capability CAP_FOWNER) can remove a file. Use this when you need the write permission, so that user can add files.
ctrl-alt-delor
  • 27,473
  • 9
  • 58
  • 102