Search code examples
linuxfileunixpermissionsacl

How to protect a file under a writable directory


I am coming across some problem with file permission and acl.
I've got a writable directory name "dir" with the permission 777 (dir rwxrwxrwx) Under dir I create a file tmp.txt (dir/tmp.txt)

I was wondering how can I stop other/group members to edit/delete the file while not changing the permission of "dir". Everyone is free take any action as they like to the other file/directory under "dir".

I was wondering maybe "setfacl" or what.


Solution

  • Whoever owns the directory can delete the files within it, even if they are owned by root.

    There are two ways to get you to almost where you want.

    Idea 1 - Sticky Bit

    $ ls -ld /tmp
    drwxrwxrwt 33 root root 1020 2020-03-14 14:06 /tmp/
    

    This is the common permissions for Unix /tmp directory. That t there at the end of the permissions denotes the sticky bit, you can set it by running:

    chmod +t /tmp
    

    The sticky bit says that even though everyone has write permission on the directory, the only ones who can delete a file under that directory are root, the directory owner, and the file's owner.

    Idea 2 - Extra Directory

    A directory cannot be deleted if it's not empty. If you put your files in a directory that's owned by you, where only you (and root) can delete files, then nobody else can delete it:

    root@playground# tree -up
    .
    `-- [drwxrwxrwx root    ]  box
        |-- [-rw-r--r-- test1   ]  f1
        `-- [drwxr-xr-x test2   ]  hello
            `-- [-rw-r--r-- test2   ]  f2
    
    2 directories, 2 files
    root@playground# su test1
    test1@playground$ rm box/hello
    rm: cannot remove ‘box/hello’: Is a directory
    test1@playground$ rm -rf box/hello/
    rm: cannot remove ‘box/hello/f2’: Permission denied