Running Docker as a Jail for Unsanitized Code

I’ve been working on creating an interactive tutorial for Perl, since places like codeacademy refuse to believe that A LOT of system administration is still performed via Perl. And there aren’t many if any resources that teach basic Perl via an Interactive shell.

So to do this I had to figure out a way to secure the environment from potential malicious code that a user could write and then execute. Docker was the solution I went with. So after installing Docker and setting up the Perl prerequisites and modules on the image, committing and running the container I had to write some code to pass the code to the container.

I went with PHP because Perl CGI is horrifying to work with directly and this a small enough project to not have to use a Perl Web Framework.

The Code

<?php
/*
* Get code from AJAX and write to chroot directory
*/
$code      = $_GET['code'];
$orig_file = uniqid() . ".pl";
$file      = "/var/www/html/domain/public/perl-course/chroot/$orig_file";
$fh        = fopen($file, 'w') or die("Can't open file");
fwrite($fh, $code);
fclose($fh);

/*
* Determine if a container is already running
* Spin up a new container if not running
*/
$id           = rtrim(shell_exec("sudo docker ps | grep perl-shell-container | awk '{print $1}'"));
$container_id = '';
if ( $id ) {
    $container_id = $id;
} else {
    $id = shell_exec("sudo docker run --name perl-shell-container -d -v /var/www/html/domain/public/perl-course/chroot/:/root/ centos-perl-nc tail -f /var/log/lastlog");
    $container_id = substr($id, 0, 12);
}

/*
* Execute perl file on the container
* and output while converting html to
* human printable code
*/
$output = shell_exec("sudo docker exec -t $container_id /usr/bin/perl /root/$orig_file 2>&1");
echo htmlentities($output);
?>

So far so good, haven’t had the host node hacked yet, but hope this helps someone who wants to do something similar.

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.