beetlebug

Run untrusted code

Build a program that runs plugins, rules, or user scripts that you did not write. Each script runs in its own thread, with a compute limit, a memory limit, and only the capabilities that you give it.

The Plugin Host window after a run of six plugins. The table has the status, the compute units, and the time of each run.

The picture shows the Plugin Host, a ztk window. It runs six plugins. Two plugins do their work. One loops with no end, one allocates with no end, one tries to read files outside its folder, and one tries to open a socket. The limits and the capabilities stop each of the four.

How it works

A plugin is a Tcl script that defines run TEXT. The host makes one thread for each run, loads the plugin with one thread::send, and calls run with a second one:

ztcl::meter create m -tenant $name
set t [thread::create -joinable -isolation $level -caps $caps -compute $compute -meter m]
set code [catch {thread::send $t $src} result]
if {$code == 0} {
    set code [catch {thread::send $t [list run $text]} result]
}
catch {thread::release $t}
catch {thread::join $t}
set units [dict get [ztcl::meter get m] units]

The isolation levels

-isolation sets what a crash or a hostile script in the thread can reach:

Level Where the thread runs
interp An interpreter of its own in the same process.
process A child process in the sandbox of the system: namespaces, a cgroup, Landlock, and seccomp on Linux.
vm A guest of ztcl::vm with its own Linux kernel, on Linux with KVM. The guest has no files of the host.

The host prints one line for each plugin. This run is at the level process, with the plugin folder as the root folder:

title-case  ok               55 units  The Quick Brown Fox Jumps Over The Lazy Dog | The Dog Sleeps
word-stats  ok               74 units  12 words, 9 different | the          3 | dog          2 | ...
spin        compute   100000000 units  compute limit reached
hog         memory        19317 units  the script used too much memory
snoop       ok               49 units  notes.txt: READ 46 bytes | /etc/passwd: couldn't open "/etc/passwd": no such file or directory | ../secret.txt: couldn't open "../secret.txt": permission denied | ...
phone-home  ok               18 units  127.0.0.1:22: invalid command name "socket" | ...

The plugin snoop has file and channels. It reads notes.txt in its folder and gets an error for each path outside it.

Run it

cd examples/usecases/untrusted-code
ztcl --root . --thread-mem 67108864 --allow thread,meter,file,channels \
    --tclsh host.tcl -isolation process

The level vm also needs the capability vm, /dev/kvm, and a guest kernel and initramfs. Isolated threads has the setup.

What is in ztcl

The isolation levels, the limits, the capabilities, and the meters are part of ztcl. The plugin host is a prototype: the plugins are short demo scripts, and all plugins share one folder.

More