Part 5 of 7 · 2 min read
chroot
Think of a guest placed in a room with a painted window: the guest sees a garden, and the real building lies beyond the wall. The analogy stops in one place: a guest can still open the door if the door is not locked, and a process with enough rights can leave a chroot.
In plain words: The system call chroot changes the root directory of the calling process, so that the path / now means a chosen directory. Files outside it can no longer be named with a path. It affects only the file view. It does not limit system calls, memory or the network, and a process that is still root inside the jail can find a way out. It is used as one layer, for example to give a service a small tree of its own files, and it is the ancestor of the mount namespace that containers use (Level 11).
A worked example. This program opens /etc/hostname, changes root to the empty directory /tmp/jail, and tries again.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static void show(const char *when) {
int fd = open("/etc/hostname", O_RDONLY);
printf("%-14s open(/etc/hostname): %s\n", when, fd >= 0 ? "ok" : strerror(errno));
if (fd >= 0) close(fd);
}
int main(void) {
show("before chroot");
if (chroot("/tmp/jail") || chdir("/")) { perror("chroot"); return 1; }
show("after chroot");
return 0;
}
before chroot open(/etc/hostname): ok
after chroot open(/etc/hostname): No such file or directory
After the change, the path /etc/hostname means /tmp/jail/etc/hostname, which does not exist. The program must call chdir("/") after chroot, as the code does, or the old working directory stays outside the jail. The error is ENOENT, not EACCES: the file is not forbidden, it is out of sight.
The key lines. chroot hides files and does not confine rights. A taken-over root process is not held by it. Use it with dropped user IDs (page 2), dropped capabilities (page 4) and a filter (section 3).
chroot
chroot is a system call that sets the root directory of a process to a given directory, so that absolute paths are looked up from there. It changes the file view only and is not a complete security boundary.
Example: after chroot("/tmp/jail"), the path /etc/hostname refers to /tmp/jail/etc/hostname.
Check yourself:
1. What does the path /etc/hostname mean after chroot("/tmp/jail")?
2. Why must the program call chdir("/") after chroot?
3. Name one thing chroot does not limit.