What is chroot
chroot is an operation in unix and unix-like operating systems that allows users to change the root directory of a process and its children to a new location on the filesystem. For example:
/
├── bin
├── usr
├── var
├── lib
├── newroot
│ ├── bin
│ ├── lib
│ ├── ...
├── ...
When you chroot a process, you are essentially creating a new filesystem environment for that process and its children. Access to files and directories is restricted within the new root directory. The environment created by chroot is sometimes called a chroot jail.
Demo: running bash
in a chroot jail
The following is a demo of running bash
in a chroot jail on Debian.
-
Create directories for bash binary and its dependencies:
mkdir -p ~/chrootjail/{bin,lib,lib64}
-
Copy
bash
binary into the new root location:cp /bin/bash ~/chrootjail/bin/bash
-
Check dependencies:
ldd /bin/bash
You should see results similar to the following:
linux-vdso.so.1 (0x00007ffd807ec000) libtinfo.so.6 => /lib/x86_64-linux-gnu/libtinfo.so.6 (0x00007f00c86fa000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f00c86f4000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f00c8520000) /lib64/ld-linux-x86-64.so.2 (0x00007f00c8869000)
Other than the vDSO
linux-vdso.so.1
, shared libraries should be copied to the new root. -
Copy the dependencies into
/chrootjail
:cp --parent \ /lib/x86_64-linux-gnu/libtinfo.so.6 \ /lib/x86_64-linux-gnu/libdl.so.2 \ /lib/x86_64-linux-gnu/libc.so.6 \ /lib64/ld-linux-x86-64.so.2 \ ~/chrootjail
The
--parent
option in thecp
command retains the parent directory structure of the files being copied, when files are being copied to a new location. -
Start a new session in
/chrootjail
:sudo chroot ~/chrootjail /bin/bash
If successful, you should see a new session:
bash-5.1#
Final words on security
While chroot is a quick approach to create a somewhat isolated filesystem, note that it was not intended to be used as a security feature. Chroot was originally designed provide a way to test and debug software in a controlled environment.
For instance, chroot is not a complete isolation at the process or network level. A process with root access can easily exit the chroot jail and access resources outside. A process running within a chroot jail may still be able to access network resources outside of the jail, or interact with other processes running on the same system.
Read more about why chroot is not a security feature on this blog by Red Hat.
For a more isolated and secure environment, consider virtualization technologies such as containers or VMs.