How to Isolate Processes Using the chroot Command in Linux

When a malicious actor compromises a Linux server, they frequently use standard system commands (like ls, cat, or rm) to explore the hard drive, steal data, or destroy critical infrastructure. To prevent an untrusted application or a highly suspicious user from wandering outside their designated directory, you must mathematically sever their connection to the true root filesystem. To create an inescapable, isolated virtual prison cell for a process, you must use the chroot (Change Root) command.

How the chroot Command Works

On a standard Linux machine, the absolute top of the filesystem is the root directory, represented by a single forward slash (/). Every single file on the hard drive exists beneath this slash. The chroot command intercepts a specific program’s system calls and violently redefines what that slash means.

If you execute a program using chroot and point it at /home/guest_user/jail/, the kernel mathematically lies to the program. The program believes that /home/guest_user/jail/ is the absolute top of the hard drive (the new /). If the program attempts to run cd .. to escape, it simply hits an invisible wall. It is physically impossible for the program to see, read, or interact with any file that exists outside the jail.

Constructing the Jail Environment

You cannot simply run chroot on an empty directory, because the jailed program will instantly crash. If you trap a user inside /home/jail/ and they try to type the ls command, it will fail because the physical /bin/ls executable file is located outside the jail.

To build a functional jail, you must meticulously copy all necessary binaries and their dependent shared libraries into the jail directory before activating the trap.

  1. Create the jail: mkdir -p /home/jail/bin
  2. Copy the bash shell: cp /bin/bash /home/jail/bin/
  3. Copy the ls command: cp /bin/ls /home/jail/bin/
  4. Use the ldd /bin/bash command to identify every required .so library file, and copy those files into /home/jail/lib/ and /home/jail/lib64/.

Activating the chroot Trap

Once the environment is fully populated with the necessary binaries and libraries, you use root privileges to execute the trap and spawn a jailed shell:

sudo chroot /home/jail /bin/bash

Your terminal prompt will change. You are now inside the jail. If you type cd / and then ls, you will not see /etc/ or /var/; you will only see the tiny /bin/ and /lib/ directories you manually copied. You have successfully isolated the process from the rest of the operating system.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.