Skip to content
Advertisement

Editing root-owned files after “unshare -Ur”

Say I am in the initial user namespace and there is an empty root-owned file in some directory:

tdiff@tp:~/temp/unshare$ sudo touch root.txt
tdiff@tp:~/temp/unshare$ ls
total 8.0K
drwxrwxr-x 2 tdiff tdiff 4.0K Oct 18 02:37 .
drwxr-xr-x 3 tdiff tdiff 4.0K Oct 18 02:37 ..
-rw-r--r-- 1 root  root     0 Oct 18 02:37 root.txt

Now I am switching to a new user namespace with unshare -Ur. In this namespace, root.txt is reported to be owned by “nobody” because original root uid(0) is not mapped to the new namespace:

tdiff@tp:~/temp/unshare$ unshare -Ur 
root@tp:~/temp/unshare# ls
total 8.0K
drwxrwxr-x 2 root   root    4.0K Oct 18 02:45 .
drwxr-xr-x 3 root   root    4.0K Oct 18 02:37 ..
-rw-r--r-- 1 nobody nogroup    0 Oct 18 02:45 root.txt

Then I use vim to edit this file. Despite giving some warnings about changing readonly file, it allows me to overwrite the contents of the file:

root@tp:~/temp/unshare# vim root.txt && cat root.txt
added from unshare

Also, if I return to the initial user namespace, the file has now changed its owner to my unpriviledged uid(1000):

root@tp:~/temp/unshare# logout
tdiff@tp:~/temp/unshare$ ls
total 12K
drwxrwxr-x 2 tdiff tdiff 4.0K Oct 18 02:47 .
drwxr-xr-x 3 tdiff tdiff 4.0K Oct 18 02:37 ..
-rw-r--r-- 1 tdiff tdiff   19 Oct 18 02:47 root.txt

How is it possible? Also, if I try to do the same with system root file (e.g. /etc/passwd), I get access denied error as expected.

UPD:

tdiff@tp:~/temp/unshare$ uname -a
Linux tp 5.4.0-51-generic #56-Ubuntu SMP Mon Oct 5 14:28:49 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

Advertisement

Answer

When you edit/save root.txt through vim, the file is renamed into root.txt~ and renamed back into root.txt as tdiff user (as well as the root user counterpart in the child user namespace) has write access in the directory ~/temp/unshare. The renaming operation changes the ownership on the resulting file to root in the child namespace which is tdiff in the father namespace.

For /etc/passwd, the same is impossible as /etc is not owned by tdiff: you don’t have access write to rename the file during the edition.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement