Detect a chroot jail from within

How to detect a chroot jail from within? In other words, how do we know if we are in a chrooted jail?


If we have root privilege, we can just compare the device/inode pair of the '/' and the '/proc/1/root/.'.

[ $(stat -c %d:%i /) != $(stat -c %d:%i /proc/1/root/.) ] && echo "In chroot jail" || echo "Not in chroot jail"

Note that if the /proc filesystem is not present, we can be sure that we're in a chrooted environment which has been poorly set up.


But what if we don't have root privilege?

In this situation, we can make use of the /proc/1/mountinfo and /proc/$$/mountinfo files, as these two files are world readable.

Let me first give you the code and then explore more on the basic backgrounds.

[ "$(awk '$5=="/" {print $1}' </proc/1/mountinfo)" != "$(awk '$5=="/" {print $1}' </proc/$$/mountinfo)" ]

The /proc/xxx/mountinfo file contains information about the mount points in the process's view of the filesystems.

So If the process reading/proc/1/mountinfois chrooted into a filesystem that's different from the global root (assuming pid 1's root is the global root), then no entry for / appears in /proc/1/mountinfo. If the process reading /proc/1/mountinfo is chrooted to a directory on the global root filesystem, then an entry for / appears in /proc/1/mountinfo, but with a different mount id.

Reference:

http://stackoverflow.com/questions/75182/detecting-a-chroot-jail-from-within

你可能感兴趣的:(linux,mount,proc,stat,chroot)