Blog | G5 Cyber Security

Code Sandboxing: A Practical Guide

TL;DR

This guide shows you how to run code safely in a sandboxed environment using Docker containers. This prevents malicious or buggy code from harming your main system.

1. Why Use Code Sandboxing?

Running untrusted code directly on your computer is risky. A sandbox isolates the code, limiting its access to your files, network, and other resources. This is crucial for:

2. Docker Basics

Docker is a popular tool for creating and managing containers. Think of a container as a lightweight virtual machine.

If you don’t have Docker installed, download it from Docker’s website and follow the installation instructions for your operating system.

3. Creating a Dockerfile

A Dockerfile is a text file that contains instructions for building a Docker image. Here’s an example for running Python code:

FROM python:3.9-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "your_script.py"]

Create a requirements.txt file listing any dependencies your code needs (e.g., requests==2.28.1).

4. Building the Docker Image

Navigate to the directory containing your Dockerfile in your terminal and run:

docker build -t my-python-app .

5. Running the Container

To run the container, use:

docker run --rm -it my-python-app

6. Resource Limits (Optional)

You can further restrict the sandbox by limiting resources:

7. Network Isolation

By default, containers have network access. To isolate the container from the network:

8. File System Isolation

The container’s file system is isolated from your host machine. Any changes made inside the container are not reflected on your host unless you explicitly mount a volume.

9. Security Considerations

Exit mobile version