Chroot Sandbox

This article discusses a way of setting up a sandbox in Linux that prevents applications run under the sandbox from making critical changes to real files. This can be useful to test applications or to test out some changes that you don't want to commit to the main files.

Directory Layout

The root of our sandbox will contain three directories:

This is the mount point for the sandbox
This is used to override files from the root.
This is where any changes will be written.

Creating the Sandbox

I used unionfs-fuse to create the sandbox with everything already in root, then mounted some additionional filesystems on top of that.

sudo unionfs-fuse -o cow,allow_other,use_ino,dev,suid,nonempty $SANDBOX/rw=RW:$SANDBOX/ro=RO:/=RO $SANDBOX/mount
sudo mount -t proc proc $SANDBOX/mount/proc
sudo mount -t devtmpfs none $SANDBOX/mount/dev
sudo mount --bind /run/shm $SANDBOX/mount/run/shm

Getting in the Sandbox

Now it is time to chroot into the sandbox.

sudo chroot $SANDBOX/mount
su -l username

Once in the sandbox, applications will only write to $SANDBOX/rw. It is possible to install applications under the sandbox, make changes for testing, and more without affecting anything outside. Because of the extra mount points, it is also possible to play games and videos.

Changes outside of the sandbox may inadvertently affect changes made in the sandbox. Files from the root can be copied to the $SANDBOX/ro directory.

mkdir $SANDBOX/ro/.unionfs
touch $SANDBOX/ro/.unionfs/tmp_HIDDEN~
mkdir $SANDBOX/ro/tmp
mkdir -p $SANDBOX/ro/home/username/.mozilla
touch $SANDBOX/ro/home/username/.mozilla/firefox_HIDDEN~
cp -a /home/username/.mozilla/firefox $SANDBOX/ro/home/username/.mozilla