Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 3 · Networking and hardening · Lesson 07 · 45 minutes

Isolate a program with chroot

After this lesson you can
  • Build a small directory tree and run a shell inside it with chroot
  • Explain why chroot is not a security boundary against root
  • Say how containers go further with namespaces and control groups
Lab files of this lesson (4)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A vendor tool must run on your server, and you do not trust it. Your team lead asks: "Can you cage it, so that it only sees its own folder? And tell me how strong the cage is." You build a cage with chroot from a shell and the libraries that it needs. You test what the program can see, and then you test if a program with root rights can leave the cage.

Recall

Which two commands do you run to give Bob a file that only he can read, and to check that a file arrived unchanged?

gpg --armor --encrypt --recipient bob@krbox.lab FILE encrypts for Bob. sha256sum on both copies, or cmp, shows that the file is the same.

Which tool shows the process that listens on a port, and what must you add to see other users' processes?

ss -tlnp, with sudo to see the processes of other users.

The idea

chroot (change root) starts a program with a new root directory. For that program the folder that you name becomes /. A path that starts with / is looked up under that folder, and the program has no path that leads out of it, except through a trick. Three reasons to use it:

UseHow
Repair a system that does not bootBoot a rescue system, mount the broken disk, and chroot into it to fix it.
Build software for a clean systemRun the build in a tree that holds only what the build needs.
A simple cage for a serviceThe service sees only its own tree.

The program can only run what is inside the new tree. A program needs its libraries: ldd PROGRAM lists them. Without them it does not start. Changing the root needs the privilege CAP_SYS_CHROOT, so in practice you must be root.

What the kernel does for a jailed program
Programopens /note.txtKernelputs the jail folder in front of the pathDiskreads note.txt in the jail folderProgramopens /note.txtKernelputs the jail folder in front of the pathDiskreads note.txt in the jail folder

Worked example

Every command that changes the root needs sudo. The commands that only build files do not.

1. Build the tree

ldd prints the shared libraries that a program loads. grep -o '/[^ ]*' keeps only the words that start with a slash, which are the paths. cp --parents FILE DIR copies a file and creates its folders below DIR, so that /bin/ls becomes jail/bin/ls. The loop copies four programs and their libraries.

mkdir -p ~/krlab/linux-advanced/chroot && cd ~/krlab/linux-advanced/chroot
mkdir jail
for prog in /bin/bash /bin/ls /bin/cat /bin/sleep; do
  cp --parents "$prog" jail/
  for lib in $(ldd "$prog" | grep -o '/[^ ]*'); do cp --parents "$lib" jail/; done
done
echo "marker inside" > jail/note.txt
find jail | sort
jail
jail/bin
jail/bin/bash
jail/bin/cat
jail/bin/ls
jail/bin/sleep
jail/lib
jail/lib64
jail/lib64/ld-linux-x86-64.so.2
jail/lib/x86_64-linux-gnu
jail/lib/x86_64-linux-gnu/libc.so.6
jail/lib/x86_64-linux-gnu/libpcre2-8.so.0
jail/lib/x86_64-linux-gnu/libselinux.so.1
jail/lib/x86_64-linux-gnu/libtinfo.so.6
jail/note.txt

Your libraries can differ on another system, and sort orders the lines by your language setting (LANG). On a newer release (Ubuntu 26.04) /bin/cat is a different program: the libraries land under jail/usr/lib, the error text has no /bin/ before cat, and chroot words its message differently. The exit codes stay the same. The file ld-linux-x86-64.so.2 is the loader, the program that loads the other libraries, and every program needs it.

2. Change the root

sudo chroot DIR PROGRAM runs PROGRAM with DIR as the root. Run three things in the jail: a listing of /, the file that you made, and a file that exists only on the real system.

sudo chroot jail /bin/ls /
sudo chroot jail /bin/cat /note.txt
sudo chroot jail /bin/cat /etc/passwd
echo "exit: $?"
bin
lib
lib64
note.txt
marker inside
/bin/cat: /etc/passwd: No such file or directory
exit: 1

The program sees only the tree that you built. /etc/passwd is there on the real system, but not in the jail. A program that is not in the tree cannot start:

sudo chroot jail /nothing; echo "exit: $?"
chroot: failed to run command ‘/nothing’: No such file or directory
exit: 127

3. Work in a shell inside the jail

Start bash in the jail. The prompt changes, because the jail has no start files. exit leaves it.

sudo chroot jail /bin/bash
bash-5.2# pwd
/
bash-5.2# ls
bin  lib  lib64  note.txt
bash-5.2# echo $UID
0
bash-5.2# exit

The shell is at /, which is the jail. Look at the line echo $UID: the user inside the jail is still number 0, which is root. The jail changes what the process can see, and not who it is.

4. See the jail from outside

Run sleep in the jail in the background. On the real system, /proc/PID/root is a link that shows the root of a process. pgrep -n -x sleep prints the process number of the newest program called sleep (-x asks for the exact name, -n for the newest), so a sleep of another user is not picked. kill PID stops one process by its number. Stop by number and not by name: pkill -x sleep would stop every process with that name.

sudo chroot jail /bin/sleep 20 &
sleep 1
PID=$(pgrep -n -x sleep)
sudo readlink /proc/$PID/root
sudo kill $PID
/home/you/krlab/linux-advanced/chroot/jail

On the real system the process has a normal place in the process list. Only its idea of / is different.

5. Leave the jail as root

This shows why chroot is not a security boundary for a program that is root. A program can call chroot again. If it then climbs with .., it gets outside the new root, because its working directory is not inside it. At the real top it sets the root again.

A root program leaves the jail
Jail folderReal systemRoot programnote.txt/etc/passwdReal root123Jail folderReal systemRoot programnote.txt/etc/passwdReal root123
  1. Root program → note.txt: reads /note.txt: works
  2. Root program → /etc/passwd (blocked): not in the jail
  3. Root program → Real root: chroot again, climb out

Give a copy of the jail the program perl, which can call chroot and chdir itself. perl also wants the file /dev/null, so make an empty one. LC_ALL=C stops locale warnings, and < /dev/null gives the program an input.

cp -a jail jail2
cp --parents /usr/bin/perl jail2/
for lib in $(ldd /usr/bin/perl | grep -o '/[^ ]*'); do cp --parents "$lib" jail2/; done
mkdir jail2/dev && touch jail2/dev/null
LIST='opendir D, "/"; print join(" ", sort grep !/^\./, readdir D), "\n"'
sudo LC_ALL=C chroot jail2 /usr/bin/perl -e "$LIST" < /dev/null
sudo LC_ALL=C chroot jail2 /usr/bin/perl -e "mkdir 'x'; chroot 'x'; chdir '..' for 1..40; chroot '.'; $LIST" < /dev/null
bin dev lib lib64 note.txt usr
bin bin.usr-is-merged boot dev etc home lib lib.usr-is-merged lib64 lost+found media mnt opt proc root run sbin sbin.usr-is-merged srv sys tmp usr var

The first line is the jail. The second line is the real root of the machine: the program is out. For this reason a jail that holds a root process and a program that can change the root is no jail. To make a chroot stronger, run the program as a normal user, put no compiler or interpreter in the tree, and put no device files in it. Remove the copy with rm -r jail2.

6. See how containers go further

A container gives a process its own view of more things than the file tree. Linux does this with two features:

  • Namespaces give a process its own copy of one kind of resource: mounts, process numbers (pid), network, host name (uts), inter-process communication (ipc), users (user) and time. ls -l /proc/self/ns shows the namespaces of your shell.
  • Control groups (cgroups) limit how much CPU, memory and input and output a group of processes may use. cat /proc/self/cgroup shows the group of your shell.

unshare runs a program in new namespaces. This changes the host name in a new uts namespace and shows that the real host name stays the same. Then it starts a program in a new pid namespace, where the program is process 1. --fork starts the program as a child, and --mount-proc gives it its own /proc.

sudo unshare --uts sh -c 'hostname krjail; hostname'
hostname
sudo unshare --pid --fork --mount-proc sh -c 'echo pid=$$; ps -e'
krjail
krbox
pid=1
    PID TTY          TIME CMD
      1 ?        00:00:00 sh
      2 ?        00:00:00 ps

A container tool such as Docker or Podman combines these layers, so a container is a much stronger cage than a chroot. It still shares the kernel with the host.

What a container adds to a jail
Control groupslimit CPU, memory and input and outputNamespacesown view of processes, network and mountsDropped privilegesmost powers removedRoot folderyour chroot jailHost kernelshared with the hostControl groupslimit CPU, memory and input and outputNamespacesown view of processes, network and mountsDropped privilegesmost powers removedRoot folderyour chroot jailHost kernelshared with the host

The same tool repairs a system that does not boot. From a live USB, sudo mount /dev/DISK /mnt mounts its root partition, sudo mount --bind /dev /mnt/dev (also for /proc and /sys) gives it the devices, and sudo chroot /mnt opens a shell inside it, where update-grub or passwd work on the broken system. sudo umount -R /mnt undoes all the mounts. This was tested on a virtual machine by mounting its own root partition a second time.

Your turn

Build a cage and test it. There are no steps here: use the commands of the worked example.

  1. Make the folder cage in ~/krlab/linux-advanced/chroot. Put in it /bin/bash, /bin/ls, /bin/cat and /bin/sleep, with their libraries.
  2. Make the file cage/data/report.txt with the one line status: green.
  3. Run cat on /data/report.txt inside the cage. Run cat on /etc/passwd inside the cage. Run a program that does not exist in the cage.
  4. Run /bin/bash -c 'echo $UID' in the cage. Use single quotes, so that the shell inside the cage expands $UID, and not yours.
  5. Start sleep 20 in the cage and read the root of that process from outside. Stop it by its number.

Remove the folder jail and the folder cage when you are done.

Check yourself

You copy /bin/ls into the jail, but "chroot jail /bin/ls" says "No such file or directory". Why?

The message can mean that the loader or a library is missing. The kernel cannot start a dynamic program without them. Run ldd /bin/ls and copy every file that it lists, to the same path.

A service runs as root inside a chroot. Why is the cage weak?

Root in the jail is root of the machine. It can call chroot again, mount devices or load modules, and so leave the jail. Run the service as a normal user.

What does a container add to a chroot?

Namespaces for processes, network, users and more, so that the program sees its own world, control groups to limit its resources, and dropped privileges. A container still shares the kernel of the host.

Why is it useful to chroot into a broken system from a rescue disk?

Inside the chroot, tools such as the package manager and the boot loader installer see the broken system as the real one, so they can repair it. Mount /dev, /proc and /sys into the tree first.

Field notes

  • For a service, prefer the sandbox options of systemd over a hand-made chroot: ProtectSystem=strict, PrivateTmp=yes, NoNewPrivileges=yes and RootDirectory=. systemd-analyze security SERVICE scores a unit.
  • Mandatory access control is a second wall that holds even when a program runs as root: AppArmor on Ubuntu (sudo aa-status lists the profiles in force) and SELinux on the Red Hat family (getenforce). A profile limits the files and powers of one program. The CIS Benchmarks ask for one of them to be on. This course does not teach how to write a profile.
  • A tool such as debootstrap builds a clean Debian or Ubuntu tree for you. It is the usual way to get a build chroot.
  • The man page chroot(2) says that it is not meant for any security purpose. Treat it as an isolation of the file tree only.
  • Files with the set-user-ID bit, and device files, in a jail give a process more power than you want. Mount a jail's folder with nosuid,nodev where you can.
  • A file descriptor that was open before the chroot stays open, and it can point outside. Close descriptors before you change the root.