ImageMagick is the go-to image conversion library in many environments. It’s written in C and doesn’t have the best track record on security. Last year, a major vulnerability called ImageTragick (yes, there’s a logo) made the news. Even Facebook turned out to be vulnerable.
While secure alternatives exist, many existing projects have a hard dependency on ImageMagick and abstracting the image conversion can be quite involved. If you find yourself in a situation where you can’t avoid using ImageMagick, sandboxing can help you mitigate the damage in the event of a compromise.
nsjail, written by Google, calls itself “a light-weight process isolation tool.” It uses a number of Linux kernel features that allow users to isolate processes in dedicated namespaces, limit file system access, put constraints on their resource usage and to filter syscalls.
My goals for this sandbox can be broken down like this:
- No network access — all images are local, so there’s no reason for ImageMagick to talk to anyone over the network
- Read-only access to the binaries, library and configuration files and write access to the directory in which images live temporarily during conversion
- Sane maximum execution times, somewhat limiting the impact of DoS attacks
- Permit only a small subset of syscalls in order to reduce the overall attack surface (making it harder for attackers to escape the sandbox)
Most distributions don’t have nsjail packages yet, so we’ll need to build from source. We’ll start with the dependencies (assuming you’re on Debian or Ubuntu):
sudo apt install autoconf bison flex gcc g++ git libprotobuf-dev libtool make pkg-config protobuf-compiler
Next, we’ll clone the code and check out the latest release (that’s version 2.2 at the time of writing).
git clone https://github.com/google/nsjail.git cd nsjail && git checkout 2.2
Building the project should be as simple as running
make. This will produce a
nsjail binary in the same directory which you can then move to
Some of the kernel features used by nsjail weren’t added until kernel 4.6, so
you might have to update your kernel or distribution. nsjail also uses the
user_namespaces feature, which is typically disabled. Append the following
/etc/sysctl.conf to enable it:
Load the configuration change by rebooting your machine or use
sudo sysctl -p.
nsjail helpfully includes a sample configuration
convert binary. This offers a good starting point for what
we need. Much of the configuration depends on how your application uses
ImageMagick. In my case, the application is