Linux – Could you explain this “chroot” /tmp directory creation

chrootlinuxmounttmp

In the following linked article they explain how to create a "chroot" /tmp directory. I'm a bit confused by what they did. Could someone explain what the following commands are doing?

Noexec and /tmp Troubleshooting

1. # mkdir -p /root/chroot /root/tmp 
2. # mount --bind / /root/chroot 
3. # mount --bind /root/tmp /root/chroot/tmp
4. # chroot /root/chroot

In the first step, why did they create /root/tmp and not /root/chroot/tmp?

Does the first mount command affects the second one? On the second step they are binding the new directory /root/chroot to the root directory. Does that mean that on the third step /root/tmp actually points to /root/chroot/root/tmp ? Where does /root/chroot/tmp comes from? That's the part I'm getting confused.

What's the logic behind this?

Best Answer

In step 2 you bind mounted / on /root/chroot.

If you create step 2.5 as ls /root/chroot you'll find all the directories of / listed; including the system's /tmp directory.

If you touch /root/chroot/test you'll see that test is also in the output of ls /. If you rm /test you'll notice that it's also gone from /root/chroot/. So / and /root/chroot/ are exactly the same place.

If you want to look in slightly more detail, run stat / and then stat /root/chroot and you'll notice that both return the same Inode. An Inode is a data structure that refers to a particular file/directory on the disk. As they both return the same Inode then both paths are pointing to exactly the same directory.

Step 3 therefore bind mounts the /root/tmp directory over the system /tmp directory within the already bind mounted /root/chroot.

When you chroot in step 4, you'll be in a chrooted / using the /tmp directory in /root instead of the system wide /tmp. This way, the chroot isn't sharing a /tmp with every other user on the system.

Related Question