Profile Picture

Alex Saveau

Alex Saveau

Build better tooling

Blog

ForkFS: make changes to your file system without consequence

Published Mar 23, 2023 • Last updated Jan 23, 2024 • 2 min read

ForkFS is a CLI app that redirects a process’s file operations to a sandbox.

Sandboxing usually has security connotations, so I want to be clear that ForkFS makes no security claims. A process can easily escape via some form of inter-process communication.

When is this useful? #

If you use one machine for long enough, your file system will end up full of leftover files from long forgotten programs. Ncdu (sorted by modified time) is extremely helpful for finding these files, but what if you could avoid creating them in the first place? That’s the primary motivator for ForkFS: if you know you’ll be transiently fiddling around with a program, you can run it under ForkFS and throw away all of its files in one go. The sandbox even works with apt!

ForkFS can also be used to test commands that may be destructive: run the command in the sandbox and then verify its results. Admittedly, this use case is probably best served by a snapshotting file system.

In general, you can open up a shell with ForkFS to easily sandbox any command.

Technical overview #

Originally, this project used a ptrace approach: intercept every syscall and rewrite its arguments such that file paths are sandboxed. The fact that this is even possible is a little mind-blowing, but I quickly realized this approach wouldn’t scale: there are too many syscalls to handle and doing so performantly would be difficult.

Instead, ForkFS is implemented as a simple wrapper over OverlayFS. I discovered that this was possible from Firejail’s defunct implementation. In brief, ForkFS:

  1. Mounts OverlayFS (and a few other FSs) into an internal directory such that the entire file system is overlaid.
  2. Changes its root directory to the mounted one.
  3. Executes the requested program.

Root privileges #

Mounting new FSs requires admin privileges which is unfortunate. Initially, ForkFS was expected to be run with sudo, but this provides a subpar experience because your environment is changed. sudo -E helps by keeping environment variables, but the home directory envvar is still modified.

Instead, ForkFS works just like sudo. To become another user (e.g. root), a file must be owned by that user and have its s permission bit set, meaning the file will take on the owner’s identity rather than the caller’s. Modern Linux applies this same idea to capabilities, meaning an executable can be granted access to do a limited set of privileged things. ForkFS supports both modes of operation.


Happy experimenting!