# chroot

## Lecture

{% embed url="https://youtu.be/C81lO7pG5aA" %}
chroot
{% endembed %}

## Example: Filesystem Isolation

`chroot()` **changes the root directory for a process and its children processes.** In other word, it changes the meaning of `/`.

For example, `chroot("/tmp/jail")` sets the root directory to be `/tmp/jail`. To get access the other directories, we must escape from this sandbox.

For this chapter, we will use [busybox](https://busybox.net/) for sandboxing purposes. Busybox packs many shell utilizes into a tiny executable file. Sometimes it is the entire user sapce on **embedded devices**.

## Effects of chroot

`chroot("/tmp/jail")` has **two effects** on the current process:

1. Change the meaning of `/` to `/tmp/jail`.
2. Change the meaning of `/tmp/jail/..` to `/tmp/jail`.

In other word, it really makes `/tmp/jail` a jail that prevents the process from going out.

However, `chroot("/tmp/jail")` does **NOT**:

* Close resources that reside outside of the jail.
* `chdir("/")` into the jail.
* Do anything else!

## Pitfall 1: Previously Open Resources

Neither of the effects of `chroot()` do anything to previously-open resources. How is this useful?

Similar to `open()` and `execve()`, Linux has `openat()` and `execveat()`:

```c
int open(char *pathname, int flags);
int openat(int dirfd, char *pathname, int flags);
int execve(char *pathname, char **argv, char **envp);
int execveat(int dirfd, char *pathname, char **argv, char **envp, int flags);
```

`int dirfd` can be a file descriptor representing any `open()`ed directory, or the special value `AT_FDCWD` (note: `chroot()` does not change the current working directory)!

## Pitfall 2: Forgetfulness

The Linux kernel does not keep track of previous chroots for a process. That is, we are able to use `chroot` again inside a jail. We are going to see how to use this idea to escape from the sandbox in babyjail.

## Is chroot Safe?

**No.** chroot is a historical way of sandboxing. It is not a good choice for modern production environment. However, it is still being used in some scenarios, so it is worthy to learn it.

Generally, a user with an effective ID of 0 (i.e., a process run as root or SUIDed to root) can always break out of a chroot, unless the chroot syscall is blocked!

{% hint style="info" %}
A replacement for chroot is **seccomp** and we will be covering it in the next section.
{% endhint %}
