Delete a file you cannot write

short · 20 min · Objective 3.3

Task

Demonstrate the permission rule that surprises everyone: deletion is controlled by the directory, not by the file. Then show the sticky bit fixing it, and confirm that permission checking stops at the first matching class.

Steps

  1. Create a shared directory that both users can write: mkdir /shared && chmod 777 /shared.
  2. As alice, create a file in it with restrictive permissions: su - alice -c 'echo secret > /shared/alice.txt; chmod 600 /shared/alice.txt'.
  3. As bob, confirm he cannot read it: su - bob -c 'cat /shared/alice.txt' fails, as expected.
  4. Now, as bob, delete it: su - bob -c 'rm -f /shared/alice.txt'. It succeeds. Explain why before continuing.
  5. Apply the sticky bit: chmod +t /shared, and confirm with ls -ld /shared that the mode ends in t.
  6. Repeat steps 2 and 4. Bob's deletion is now refused.
  7. Demonstrate first-class-wins: create a file owned by alice with mode 077 and have alice try to read it. She cannot, although group and other can.

Verify

ls -ld /shared | cut -c1-10             # must end in t after step 5
su - alice -c 'echo test > /shared/a2.txt'
su - bob -c 'rm -f /shared/a2.txt' 2>&1 | grep -qi 'not permitted' && echo "sticky works"
touch /tmp/odd && chown alice /tmp/odd && chmod 077 /tmp/odd
su - alice -c 'cat /tmp/odd' 2>&1 | grep -qi 'denied' && echo "owner bits win"

Both echoes must print. The second is the counterintuitive one: alice owns the file, the owner bits are 0, and the permissive group and other bits are never consulted because the check stopped at the first matching class.

Notes

/tmp on every real system is drwxrwxrwt for exactly the reason step 5 demonstrates -- everyone needs to create files there, and nobody should be able to remove anyone else's.