Part 3 · Networking and hardening · Lesson 07 · 45 minutes
Isolate a program with chroot
- 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
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:
| Use | How |
|---|---|
| Repair a system that does not boot | Boot a rescue system, mount the broken disk, and chroot into it to fix it. |
| Build software for a clean system | Run the build in a tree that holds only what the build needs. |
| A simple cage for a service | The 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.
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 | sortjail
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.txtYour 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: 1The 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: 1273. 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/bashbash-5.2# pwd
/
bash-5.2# ls
bin lib lib64 note.txt
bash-5.2# echo $UID
0
bash-5.2# exitThe 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/jailOn 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.
- Root program → note.txt: reads /note.txt: works
- Root program → /etc/passwd (blocked): not in the jail
- 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/nullbin 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 varThe 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/nsshows 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/cgroupshows 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 psA 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.
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.
- Make the folder
cagein~/krlab/linux-advanced/chroot. Put in it/bin/bash,/bin/ls,/bin/catand/bin/sleep, with their libraries. - Make the file
cage/data/report.txtwith the one linestatus: green. - Run
caton/data/report.txtinside the cage. Runcaton/etc/passwdinside the cage. Run a program that does not exist in the cage. - Run
/bin/bash -c 'echo $UID'in the cage. Use single quotes, so that the shell inside the cage expands$UID, and not yours. - Start
sleep 20in 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=yesandRootDirectory=.systemd-analyze security SERVICEscores a unit. - Mandatory access control is a second wall that holds even when a program runs as
root: AppArmor on Ubuntu (sudo aa-statuslists 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
debootstrapbuilds 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,nodevwhere you can. - A file descriptor that was open before the
chrootstays open, and it can point outside. Close descriptors before you change the root.