We are going to design a safe sandbox for untrusted user code. The sandbox must provide:
- Isolation: The untrusted code should not be able to access the host system or other processes.
- Resource Caps: Limit CPU, memory, disk, and network usage.
- Policy: Define what actions are allowed and what are not.
We can use a combination of techniques:
- For isolation: Use containers (like Docker) or virtual machines, or even seccomp, namespaces, and chroot in Linux.
- For resource caps: Use cgroups (for CPU, memory, disk I/O) and network namespaces with traffic control (for network).
- For policy: Define a set of allowed system calls (using seccomp) and file system access (using chroot or mount namespaces).
However, note that the user code is untrusted and we want to run arbitrary code (in a specific language?).
Since the problem does not specify the language, we assume we are running a compiled binary or a script with an interpreter.
Steps:
-
Create a minimal file system (rootfs) that contains only the necessary libraries and binaries for the user code to run.
This can be done by using a minimal base image (like alpine) and then adding the required interpreter and libraries.
-
Use Linux namespaces to isolate:
- PID namespace: so the process cannot see other processes.
- Network namespace: to isolate network (and we can block network by not setting up any interface, or use a virtual interface with limits).
- Mount namespace: to control the file system view (we will mount a minimal rootfs and maybe a tmpfs for /tmp).
- UTS namespace: to isolate hostname.
- IPC namespace: to isolate inter-process communication.
- User namespace: to map the user to a non-root user inside the container.
-
Use cgroups to limit:
- CPU: set a CPU quota (e.g., 0.1 CPU) or use CPU shares.
- Memory: set a memory limit (e.g., 100MB).
- Disk: use a separate disk quota or use a tmpfs and limit its size, or use a loopback device with a fixed size and set I/O limits.
- Network: if we allow network, we can set bandwidth limits.
-
Use seccomp to filter system calls. We can start with a default deny policy and then allow only the necessary syscalls for the user code to run.
-
Drop all capabilities (or only keep a minimal set) and run as an unprivileged user.
-
Set resource limits (ulimit) for things like number of processes, file size, etc.
However, note that setting up all this from scratch is complex. Alternatively, we can use existing container runtimes (like Docker, runc, podman) but with a very restrictive profile.
But the problem says "create", so we are going to design a system, not necessarily implement every detail.
We can break down the sandbox into:
a. Preparation:
- Build a minimal rootfs (or use an existing one) with only the necessary tools.
- Create a user inside the container (with a known UID/GID) and set the home directory to a writable tmpfs (or a directory that we mount).
b. Runtime:
- Use a container runtime (like runc) or write a custom launcher that uses the Linux primitives (unshare, setrlimit, etc.) to set up the namespaces and cgroups.
c. Policy:
- Define a seccomp filter (in JSON format for runc, or using libseccomp).
- Define the allowed file system paths (only the minimal rootfs and maybe a specific directory for user input/output).
d. Monitoring:
- We should also have a way to monitor the process and kill it if it exceeds the limits (but cgroups should handle that).
However, note that we are not allowed to run as root? In practice, to set up cgroups and namespaces we need privileges.
We can do:
Option 1: Run a privileged sandbox manager (as root) that sets up the sandbox and then drops privileges.
Option 2: Use user namespaces to map the root inside the container to an unprivileged user outside. Then we can set up cgroups without full root? But note that cgroup v2 can be delegated to user namespaces, but it's complex.
Given the complexity, let's assume we have a privileged helper (the sandbox manager) that runs as root and sets up the sandbox for each user code execution.
Steps for the privileged helper:
-
Receive a request to run a user code (with the code and possibly the language/runtime).
-
Prepare the rootfs (if not already prepared) and copy the user code into the container's filesystem (maybe in /app).
-
Set up a new cgroup for the process (with the specified limits).
-
Set up the namespaces (unshare) and then in the new namespace:
- Mount the rootfs (read-only except for specific writable directories like /tmp and /app).
- Set the hostname, domainname, etc.
- Create a new user and set the UID/GID mapping (if using user namespace).
- Set the working directory to /app (where the user code is).
- Drop privileges (setuid to the unprivileged user).
- Apply seccomp filter.
- Set resource limits (ulimit).
- Execute the user code (with the specified command, e.g.,
python3 /app/script.py).
-
Wait for the process to finish and then clean up.
But note: the user code might be malicious and try to break out. So we must be very careful.
Alternatively, we can use an existing sandboxing solution like:
- gVisor (from Google) which is a user-space kernel that runs containers.
- Firecracker (from AWS) which uses microVMs.
- Or even simpler: use Docker with a very restrictive profile.
However, the problem says "create", so we are expected to design a system.
Let's design a system that uses:
- For isolation: Linux namespaces (pid, net, mnt, uts, ipc, user) and seccomp.
- For resource caps: cgroups (v2) and ulimit.
- For policy: a combination of seccomp (syscalls) and file system access (via mount namespace and read-only rootfs with specific tmpfs mounts).
Steps in code (pseudocode):
-
Create a new cgroup (or use a pre-created one) and set the limits:
- cpu.max: "10000 100000" (10% of one CPU)
- memory.max: "100M"
- io.max: for each block device, set limits if needed.
- For network, we can set up a virtual interface and use tc to shape traffic, or just not provide any network (if we don't need network).
-
Unshare the necessary namespaces (CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC).
-
In the user namespace, map the current user to root inside (if we want to have root inside but unprivileged outside). But note: we want to run as non-root inside too.
We can do:
- In the user namespace, map UID 0 to the current user's UID (so we are root in the user namespace) and then we can set up the other namespaces and then drop privileges by setting the UID to a non-zero UID (which is mapped to the same outside UID).
Alternatively, we can create a new user and group inside the container and use that.
-
Mount the rootfs (read-only) and then mount a tmpfs on /tmp and on /app (if we want to write) or a specific directory that we bind mount from the host (but must be safe).
We can do:
mount(rootfs, "/", NULL, MS_REC | MS_SLAVE, NULL);
mount(rootfs, "/", NULL, MS_REC | MS_PRIVATE, NULL);
Then mount the rootfs as read-only at "/".
Then mount a tmpfs on "/tmp" and set mode 1777.
And then bind mount the user code (from the host) to /app (with the appropriate permissions).
-
Set the hostname to something like "sandbox".
-
Set the UID/GID to the unprivileged user (e.g., 1000:1000) inside the container. But note: we are in a user namespace, so we can map any UID/GID to the outside. We can create a new user and group in the container and use that.
-
Apply seccomp filter: only allow a set of syscalls that are safe. For example, for a Python script we might need: read, write, open, close, fstat, mmap, mprotect, munmap, brk, access, pipe, select, epoll, wait4, etc. But we must be very restrictive.
We can generate a seccomp filter based on the language runtime. Alternatively, we can use a default deny and then allow only the necessary ones.
However, note that some syscalls are needed for basic operation. We can start with a minimal set and then adjust as needed.
-
Set resource limits (ulimit) for:
- nproc: 10
- fsize: 0 (no file creation)
- as: 100M (virtual memory)
- cpu: 5 seconds (but we have cgroup for CPU, so maybe not needed)
-
Then exec the user code.
-
Wait for the process and then clean up the cgroup and namespaces.
However, note that if the user code forks, we have to make sure that all processes are in the same cgroup and namespaces. By default, when we unshare the PID namespace, the forked processes are in the same PID namespace. And we can set the cgroup for the whole cgroup (which will include all children).
But we must also set the cgroup for the process before we start the user code? Actually, we can set the cgroup for the process and then when it forks, the children are in the same cgroup (if we use cgroup v2 and the delegation is set).
Implementation:
We can write a C program that does:
// Step 1: Set up cgroup
// Step 2: Unshare namespaces
// Step 3: Mount rootfs and other mounts
// Step 4: Set UID/GID and drop privileges
// Step 5: Set seccomp
// Step 6: Set ulimits
// Step 7: Exec user code
But note: we are root (in the initial user namespace) and we want to become non-root in the new user namespace. We have to do:
- Unshare user namespace (CLONE_NEWUSER). Then we are root in the new user namespace.
- Then we can map the UID/GID. We write to /proc/self/uid_map and /proc/self/gid_map.
- Then we can set the GID and UID to the desired non-root user (which is mapped to an unprivileged user outside).
However, note that we cannot set the UID/GID until we have written the maps. And we cannot write the maps until we are in the user namespace.
So:
unshare(CLONE_NEWUSER);
// write to /proc/self/uid_map and /proc/self/gid_map to map the desired UID/GID.
Then we can setgid and setuid to the desired user.
But note: the user code will run as that user.
However, we also want to set up the other namespaces. We can do:
unshare(CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC);
But note: when we unshare multiple namespaces, we have to do it in one call or multiple? The unshare call can take multiple flags.
Then we do the mounts, then set the user, then seccomp, then ulimits, then exec.
But note: we must be careful about the order. The mount namespace must be set before we mount, and the user namespace must be set before we map the UID/GID.
However, the unshare call will create new namespaces and then we are in them.
Steps:
-
unshare(CLONE_NEWUSER | ...) -> we are now in the new namespaces.
-
Write to /proc/self/uid_map and /proc/self/gid_map to map the UID/GID.
-
Then set the GID and UID to the desired user (which is now mapped to an unprivileged user outside).
-
Then mount the rootfs (in the new mount namespace).
-
Then set the hostname (in the new UTS namespace).
-
Then set up the network (in the new network namespace). We might not set up any network, so the process will have no network.
-
Then set the seccomp filter.
-
Then set the resource limits (ulimit).
-
Then exec.
But note: the user code must be executable. We have to have the interpreter in the rootfs.
We also have to consider that the user code might be in a different language. We can have a base image with multiple interpreters, or we can require the user to specify the command.
Let's assume we are given a command to run (like "python3 script.py") and we have a rootfs that contains python3.
We also have to copy the user code into the container's filesystem (in the mount namespace we are about to set). We can do that by bind-mounting a directory from the host that contains the user code.
But note: we are in a new mount namespace, so we can mount the host's directory (with the user code) into the container. However, we must be careful because the user code might be malicious and try to break out by using the mount namespace? But we are the only one in the mount namespace and we are setting up the mounts.
Alternatively, we can copy the user code into a tmpfs and then mount that as the /app directory.
Steps for the user code:
- We have a directory on the host with the user code (let's say /tmp/user_code_xyz).
- We mount a tmpfs on /app and then copy the user code there? But that requires an extra step and we have to be careful about the copy.
Alternatively, we can bind mount the host directory to /app, but then the user code can modify the host directory? We don't want that.
So we can:
- Create a directory on the host that is only for this sandbox (and is empty) and then copy the user code there (as root) and then bind mount it as read-only? But then the user code cannot write to its own directory.
We want the user code to be able to write to a temporary directory. So we can:
- Mount a tmpfs on /tmp (with mode 1777) and then set the working directory to /app (which is read-only) and then the user code can write to /tmp.
But what if the user code wants to write to its own directory? Then we have to make /app writable? But then the user code can modify its own code? That might be acceptable.
Alternatively, we can have two mounts:
- /app: read-only, contains the user code.
- /workspace: a tmpfs (or a writable bind mount from a host directory that we created for this session) where the user code can write.
Then we set the working directory to /workspace, and the user code is in /app.
But the user code might expect to be run from the same directory as the script? We can adjust.
Alternatively, we can copy the user code to /workspace and then run from there? But then we are copying the code to a writable directory, which might be okay.
However, if we copy the code to a writable directory, then the user code can modify itself? That might be a security issue? Not necessarily, but it could be used to hide malicious code? But we are already running it.
Let's decide:
We will:
- Have a minimal rootfs that is read-only.
- Mount a tmpfs on /tmp (for temporary files).
- Mount a tmpfs on /workspace (for user code to write). We will copy the user code from the host to /workspace and then set the working directory to /workspace.
Steps:
- Before unshare, we copy the user code from the host (a directory) to a temporary directory (on the host) that we will use as the /workspace.
- Then in the sandbox, we mount a tmpfs on /workspace and then copy the user code from the host's temporary directory to the tmpfs? But that's two copies.
Alternatively, we can:
- Create a directory on the host for this sandbox (e.g., /tmp/sandbox_xyz).
- Copy the user code there (as root).
- Then in the sandbox, we bind mount that directory as /workspace (and then we can make it read-write? but then the host directory is writable by the user code? and the user code can break out of the sandbox by writing to the host directory? No, because we are in a mount namespace and the bind mount is only visible inside the sandbox, but the host directory is real and the user code can write to it? Actually, yes, because the bind mount is the same inode. So if we bind mount a host directory that is writable by the sandbox user (and we set the UID/GID mapping to an unprivileged user) then the user code can write to the host directory? That might be a problem if the host directory is not isolated.
So we must ensure that the host directory we use for /workspace is only accessible by the sandbox and is cleaned up afterwards.
Alternatively, we can use a tmpfs and then copy the user code into it. That way, the user code cannot write to the host.
Steps:
- We have the user code on the host in a directory (read-only for us, the root).
- We create a tmpfs in the sandbox for /workspace.
- Then we copy the user code from the host (from the read-only directory) to the tmpfs.
How to copy? We can do:
- Before we unshare, we are root and we can read the host directory and then write to a tmpfs? But we are going to unshare and then we are in the new mount namespace.
We can do:
- Step 1: unshare the mount namespace (so we have a private mount namespace).
- Step 2: mount the rootfs (read-only) at /.
- Step 3: mount a tmpfs at /workspace.
- Step 4: copy the user code from the host (which is still accessible because we haven't changed the root) to /workspace? But note: we have changed the mount namespace, but the host's directory is still mounted? Actually, when we unshare the mount namespace, we get a copy of the parent's mount table. Then we mount the rootfs over /, so we cannot see the host's / anymore? Wait:
We are in the new mount namespace and we have the same mounts as the host initially. Then we mount the rootfs over /, so now / is the rootfs and we cannot see the host's /.
So we cannot copy from the host's directory because it is hidden by the rootfs mount.
So we have to copy the user code before we mount the rootfs? But then we are in the host's mount namespace and we don't want to expose the host's files.
Alternatively, we can:
- Mount the rootfs at a different mount point (say /rootfs) and then pivot_root to /rootfs? But pivot_root is tricky.
Another idea:
- We can create a temporary directory on the host (say /tmp/sandbox_xyz) and then bind mount that to /workspace in the sandbox. And then we copy the user code from the host's original location (which is in the host's filesystem) to /tmp/sandbox_xyz (as root) before we start the sandbox? Then we bind mount /tmp/sandbox_xyz to /workspace in the sandbox.
But then the user code can write to /tmp/sandbox_xyz? And that is a directory on the host. We can set the permissions of /tmp/sandbox_xyz to be owned by the UID that we will use inside the sandbox? But we are going to map that UID to an unprivileged user outside? Actually, we are going to run as a non-root user inside the sandbox, and that user will be mapped to an unprivileged user outside (if we use user namespace). But the directory /tmp/sandbox_xyz is owned by root? We can change the ownership to the UID that we will use inside the sandbox? But that UID is not the same as the outside UID? Actually, in the user namespace, we map UID 0 (inside) to the outside UID of the sandbox manager? Or we map a non-root UID inside to the outside UID?
Let me clarify:
We are going to run the sandbox manager as root (on the host). We want to run the user code as non-root inside the sandbox.
We can:
- Create a user and group on the host for the sandbox (say 1000:1000) and then in the user namespace, map UID 0 (inside) to 1000 (outside) and map GID 0 to 1000 (outside). Then we set the UID and GID to 0 inside the container? But then we are root inside the container? That is not what we want.
Alternatively, we can:
- In the user namespace, map UID 1000 (inside) to 1000 (outside) and then set the UID to 1000 inside the container. Then we are non-root inside and outside.
So:
- We create a user and group on the host (if not exists) with UID/GID 1000.
- Then in the user namespace, we map:
UID: 0 -> 1000 (so that we can become root inside the user namespace? Actually, we don't need to be root inside. We can map 1000 -> 1000 and then set the UID to 1000.
But note: when we unshare the user namespace, we are root (UID 0) in the new user namespace. Then we write to /proc/self/uid_map:
0 1000 1
This maps UID 0 in the new user namespace to UID 1000 on the host.
Then we set the UID to 1000? But 1000 in the new user namespace is not mapped? We only mapped 0.
We have to map a range. We want to have a non-root user inside (say 1000) and map it to 1000 on the host? Then we can do:
0 1000 1 -> maps UID 0 (inside) to 1000 (outside)
1000 1000 1 -> maps UID 1000 (inside) to 1000 (outside) ? But that would require two mappings.
Actually, we can map:
0 1000 1 -> then UID 0 inside is 1000 outside.
Then we set the UID to 0? Then we are 1000 outside.
But then inside we are root (in the user namespace) but outside we are 1000. That's okay because we are in a user namespace and we are not privileged on the host.
Then we can set the GID similarly.
Then we can set the UID to 0 (which is 1000 outside) and then we are root in the user namespace but unprivileged on the host.
Then we can set up the other namespaces and then drop the capabilities? Actually, in the user namespace, we have all capabilities, but they are mapped to the outside user (which is unprivileged) so they are not effective.
Then we can set the UID and GID to 1000? But 1000 inside is not mapped? We only mapped 0.
We can map:
0 1000 1 -> UID 0 inside -> 1000 outside.
1 1001 1 -> UID 1 inside -> 1001 outside, etc.
But we don't need to map every UID. We just need the one we are going to use.
Alternatively, we can map:
0 1000 1 -> then set the UID to 0, and then we are 1000 outside.
Then we can create a user and group inside the container (with UID 0 and GID 0) and then we are root inside the container? But we don't want to be root inside the container? Actually, being root inside the container (but in a user namespace) is safe because the host sees us as 1000.
But then we have all capabilities in the user namespace, but they are mapped to an unprivileged user on the host, so we cannot do any privileged operation on the host.
Then we can set up the cgroup and other namespaces? But note: to set up cgroups we need to be root? Actually, with cgroup v2 and user namespace delegation, we can set up cgroups without being root on the host? It's complicated.
Given the complexity, let's assume we have a privileged sandbox manager that runs as root on the host and does not use user namespaces for the entire sandbox, but only for the process? Actually, we are going to run the user code as an unprivileged user (on the host) but in separate namespaces.
So:
- The sandbox manager runs as root.
- It sets up a cgroup and then forks.
- In the child, it unshares the namespaces (including user namespace) and then in the user namespace, it maps the UID 0 to the UID of an unprivileged user (say 1000) and then sets the UID and GID to 0 (which becomes 1000 on the host). Then it drops capabilities? Actually, in the user namespace, we have all capabilities but they are mapped to the unprivileged user, so they are not effective on the host.
Then we can set up the other namespaces and then run the user code as root inside the user namespace (but unprivileged on the host). Then we can set the UID to 1000 inside? But 1000 inside is not mapped? We only mapped 0.
We can map:
0 1000 1 -> so UID 0 inside is 1000 outside.
1000 1000 1 -> then UID 1000 inside is 1000 outside? But that would require mapping two IDs.
Actually, we can map a range:
0 1000 2 -> maps UID 0 and 1 inside to 1000 and 1001 outside.
Then we set the UID to 1000? Then we are 1000 outside.
But then inside we are not root? We are 1000 inside, and 1000 inside is mapped to 1000 outside.
So we can do:
In the user namespace, we map:
UID: 0 -> 1000 (so that we can become root inside, but then we are 1000 outside)
Then we set the UID to 1000? But 1000 inside is not mapped? We only mapped 0.
We can map 1000 inside to 1000 outside? Then we set the UID to 1000 and we are 1000 outside.
But then we are not root inside? We are 1000 inside.
We don't need to be root inside. We want to be an unprivileged user inside.
So we can:
- Map 1000 inside to 1000 outside.
- Then set the UID to 1000.
Then we are 1000 on the host and 1000 inside.
But then we don't have the ability to set up the mount namespace? Actually, we are in the user namespace and we are 1000 inside, but we are root in the user namespace? Because we are the first process in the user namespace? Actually, in the user namespace, the first process (us) has all capabilities and UID 0. But then we set the UID to 1000, and then we drop capabilities? We can drop capabilities by setting the permitted and effective sets to empty.
But note: we are setting up the mount namespace and mounting the rootfs. For that, we need CAP_SYS_ADMIN in the user namespace? Actually, in the user namespace, we have CAP_SYS_ADMIN because we are root in the user namespace. But that capability is not effective on the host.
So we can mount.
Then we set the UID to 1000 and then we drop capabilities.
Then we exec the user code.
So steps:
1. Create a cgroup and set limits (as root).
2. Fork.
3. In the child:
- unshare(CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC);
- Write to /proc/self/uid_map: "1000 1000 1\n" (map UID 1000 inside to 1000 outside)
- Write to /proc/self/gid_map: "1000 1000 1\n"
- setgid(1000); setuid(1000);
- Now we are UID 1000 inside and outside.
- Drop capabilities: set the permitted and effective capability sets to empty? Actually, we are in the user namespace and we are not privileged on the host, so we don't have any capabilities on the host. But inside the user namespace, we have all capabilities? We can drop them by setting the bounding set? Actually, we can call prctl(PR_CAPBSET_DROP, ...) for each capability? But note: in the user namespace, we have all capabilities, but they are not effective on the host.
However, we want to drop capabilities inside the user namespace? Actually, we don't want the user code to have any capabilities. So we should drop them.
But note: we are setting up the sandbox and we already did the mounts. So we can drop capabilities after we set up the mounts? Actually, we set up the mounts as UID 0 in the user namespace? We set the UID to 1000 before mounting? We cannot mount as non-root? Actually, we mounted as root in the user namespace (because we were root before setuid). Then we set the UID to 1000 and then drop capabilities.
So:
- After unshare, we are root in the user namespace (UID 0) and we have all capabilities.
- We write the uid_map and gid_map.
- Then we mount the rootfs (as root in the user namespace).
- Then we set the UID and GID to 1000.
- Then we drop capabilities (by setting the permitted and effective sets to empty, and also drop the bounding set?).
But note: the mount operation was done when we were root in the user namespace, so it's okay.
4. Then we set up the other namespaces (we already did in the unshare, but we have to set the hostname, etc.)
5. Then we set the seccomp filter.
6. Then we set the resource limits (ulimit).
7. Then we exec the user code.
But note: the user code will run as UID 1000 (inside and outside) and with no capabilities.
However, we set up the cgroup as root and then we added the process to the cgroup? We have to add the process to the cgroup after we fork? Actually, we can add the process to the cgroup by writing its PID to the cgroup.procs file. But we are in the child and we are about to set up the namespaces. We can do:
In the parent (after fork):
- Write the child's PID to the cgroup.procs.
But note: the child's PID in the parent's PID namespace is different from the child's PID in the child's PID namespace? Actually, when we create a new PID namespace, the child becomes PID 1 in the new namespace. But the parent sees the child with a different PID.
We want to add the process (and all its children) to the cgroup. We can do:
- In the parent, after fork, we write the child's PID (in the parent's namespace) to the cgroup.procs? But then the child is in the cgroup? And when the child creates a new PID namespace, it remains in the same cgroup? Yes, because cgroups are hierarchical and the process is in the cgroup when it is added, and then when it forks, the children are in the same cgroup.
So we can:
- In the parent, after fork, write the child's PID to the cgroup.procs.
But note: we are going to unshare the PID namespace in the child. The child's PID in the parent's namespace is the one we write, but in the child's PID namespace, the child is PID 1. But the cgroup is tied to the task (the process) and not the PID? Actually, the cgroup.procs file expects the PID in the caller's PID namespace? It's the same task.
So we can write the child's PID (from the parent) to the cgroup.procs and then the child (and its children) will be in that cgroup.
8. Then we wait for the child to finish.
So the parent does:
- Create cgroup and set limits.
- fork.
- In the parent: write child's PID to cgroup.procs and then wait.
- In the child: do the unshare and setup.
But note: the child might exec before the parent writes the PID? Actually, the parent writes the PID immediately after fork, and then the child does the setup and then execs. So the child is in the cgroup during the setup? We want the setup to be in the cgroup? Yes, so that the setup (mounting, etc.) is also limited? But the setup is done by the child before it execs, and we want that to be limited too? Actually, we want the user code to be limited, but the setup is done by the sandbox manager (which is privileged) and we don't want to limit that? Actually, the child is running the setup code and then the user code. We want the user code to be limited, but the setup code is part of the sandbox and should be fast and not use many resources. So we can add the child to the cgroup immediately after fork? Then the setup code is also limited? That might be acceptable because the setup code is trusted and we control it.
Alternatively, we can do the setup in the parent and then only add the child to the cgroup after we exec? But we cannot because the child is already running.
So we accept that the setup code is also in the cgroup and subject to the same limits? That might be okay because the setup code is minimal.
However, if the setup code does a lot of work (like mounting a large rootfs) then it might hit the limits? We can set the limits to be high enough for the setup, but then the user code might abuse that? Actually, the setup code is trusted and we control it.
Alternatively, we can do:
- In the child, after unshare and before mounting, we can write our own PID to the cgroup.procs? But we are in a new PID namespace? Actually, we are in the child's PID namespace (which is new) and we are PID 1. But the cgroup.procs file is in the host's PID namespace? Actually, the cgroup filesystem is mounted in the host's mount namespace? We are in a new mount namespace, but we haven't mounted the cgroup filesystem? We are using the host's cgroup filesystem? Actually, we are going to use the host's cgroup filesystem (mounted at /sys/fs/cgroup) and we are in the host's mount namespace? No, we are in a new mount namespace, but we haven't changed the root yet? Actually, we are going to mount the rootfs and then change the root? We haven't done that yet.
This is getting very complex.
Given the time, let's assume we have a privileged sandbox manager that does:
1. Create a cgroup and set limits.
2. fork.
3. In the parent: write the child's PID (in the parent's PID namespace) to the cgroup.procs.
4. In the child:
- unshare the namespaces.
- set up the user namespace (map UID 1000 to 1000, set UID to 1000).
- mount the rootfs (read-only) and other mounts (tmpfs for /tmp and /workspace).
- copy the user code from the host (from a directory that we prepared) to /workspace (in the tmpfs).
- set the hostname.
- set the seccomp filter.
- set the resource limits (ulimit).
- drop capabilities (if any).
- chdir to /workspace.
- exec the user code.
Then the parent waits for the child.
But note: the copy of the user code from the host to the tmpfs: we are in the child's mount namespace and we have mounted the rootfs at /, so we cannot see the host's directory? We have to copy the user code before we mount the rootfs? But then the user code is in the host's filesystem and we are going to mount the rootfs over /, so we lose it.
So we have to copy the user code to a place that is not covered by the rootfs mount? We can:
- Mount the rootfs at /rootfs (temporarily) and then pivot_root? But that's complex.
Alternatively, we can:
- In the child, before we mount the rootfs, we are in the host's mount namespace (because we unshared the mount namespace, but we haven't mounted anything yet). So we can see the host's files.
Then we:
1. Create a directory for the user code in the host (say /tmp/sandbox_xyz) and copy the user code there (as root, in the parent?).
2. Then in the child, we mount a tmpfs at /workspace.
3. Then we copy the user code from /tmp/sandbox_xyz to /workspace? But /tmp/sandbox_xyz is in the host's mount namespace and we are in the child's mount namespace? Actually, we unshared the mount namespace, so we have a copy of the parent's mount table. So /tmp/sandbox_xyz is visible.
4. Then we mount the rootfs at / (and then we cannot see /tmp/sandbox_xyz anymore because it is under /? Actually, we mount the rootfs at /, so now / is the rootfs and we cannot see the host's /tmp/sandbox_xyz because it is under the old /.
So we have to copy from /tmp/sandbox_xyz to /workspace before we mount the rootfs at /.
But /workspace is a tmpfs that we mount at /workspace (which is under the old /). Then we mount the rootfs at /, and then /workspace is still there? Because we mounted it at /workspace, and then we mount the rootfs at /, so /workspace is still accessible because it is a separate mount point.
So:
Step 1: mount a tmpfs at /workspace (in the child's mount namespace, which is a copy of the parent's).
Step 2: copy the user code from /tmp/sandbox_xyz (which is visible in the parent's mount namespace, and we are in the child's mount namespace which is a copy) to /workspace.
Step 3: mount the rootfs at / (now / is the rootfs, but /workspace is still the tmpfs because it is a separate mount point).
Then we can chdir to /workspace and run the user code.
But note: the user code is in /workspace (tmpfs) and the rootfs is at / (read-only).
And we have /tmp (also a tmpfs) and /workspace.
And the user code can write to /workspace and /tmp.
And the user code cannot see the host's /tmp/sandbox_xyz because it is under the old / (which is now covered by the rootfs).
So that works.
Steps in the child:
unshare(CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC);
// Write uid_map and gid_map: map 1000 -> 1000
// setgid(1000); setuid(1000);
// Mount a tmpfs at /workspace
mount("tmpfs", "/workspace", "tmpfs", 0, NULL);
// Copy the user code from /tmp/sandbox_xyz (on host) to /workspace
// How to copy? We can use system("cp -r /tmp/sandbox_xyz/* /workspace/")? But we don't have cp? We can use a library function to copy? Or we can do it in the parent and then we don't need to copy? But we want the user code in the tmpfs so that the host's directory is not modified.
Alternatively, we can bind mount /tmp/sandbox_xyz to /workspace? But then the user code can modify the host's directory? We don't want that.
So we copy.
We can use the `copy` function from the C library? But we have to be careful about the files.
Alternatively, we can do:
system("cp -r /tmp/sandbox_xyz/* /workspace/");
But we don't have system? We are in a minimal environment? We are about to mount the rootfs, so we don't have the standard utilities.
We can use the `clone` and `exec` to run `cp`? But we don't have `cp` in the rootfs? We are going to mount the rootfs after we copy? We are copying from the host's directory (which is visible) to the tmpfs (which is also visible). We can use the `copy_file_range` or `sendfile` system calls? But that's low-level.
Alternatively, we can do the copy in the parent? But the parent is privileged and we want to avoid that because the parent is the sandbox manager and we don't want to copy the user code as root? Actually, we can copy the user code to /tmp/sandbox_xyz as root, and then in the child we copy from /tmp/sandbox_xyz to /workspace (as UID 1000). But then the child has to copy, and we don't have the utilities.
We can write a small C program that does the copy and then statically link it and put it in the rootfs? But then we are adding complexity.
Alternatively, we can bind mount the host's directory (with the user code) to /workspace and then make it read-only? But then the user code cannot write to its own directory? We want the user code to be able to write to its own directory? Actually, we want the user code to be able to write to /workspace? If we bind mount the host's directory as read-only, then the user code cannot write to /workspace.
We can:
- Create a directory on the host for the user code (read-only) and then bind mount it to /app (read-only) and then have a separate /workspace (tmpfs) for writing.
Then we don't need to copy the user code to /workspace? We can run the user code from /app? But the user code might write to its own directory? Then we have to make /app writable? But then the user code can modify the host's directory? If we bind mount a host directory as writable, then the user code can modify the host's directory.
So we want the user code to be in a read-only location and have a separate writable location.
We can:
- Have the user code in a read-only bind mount (from the host) at /app.
- Then have a writable tmpfs at /workspace.
Then the user code can write to /workspace, but not to /app.
And we run the user code from /app? But the user code might be a script that expects to be in the same directory? We can set the working directory to /workspace and then run the script from /app? Or we can set the working directory to /app? But then the user code cannot write to the current directory? It can write to /workspace.
We can set the working directory to /workspace and then the user code is in /app. The user code can access /app (read-only) and write to /workspace.
Then we don't need to copy the user code.
Steps:
- In the child, before mounting the rootfs, we bind mount the host's user code directory (which is read-only for the host) to /app (in the child's mount namespace). But we are going to mount the rootfs at /, so we have to mount /app before we mount the rootfs? Actually, we can:
mount the host's user code directory to /app (in the child's mount namespace).
mount a tmpfs at /workspace.
Then mount the rootfs at /.
Then the /app and /workspace are still there because they are separate mount points.
Then we set the working directory to /workspace and run the command with the user code in /app.
Example: the user code is a Python script at /app/script.py, then we run:
python3 /app/script.py
from /workspace.
And the user code can write to /workspace.
And /app is read-only (because the host's directory is read-only? We can mount it as read-only).
So:
In the child:
unshare(...);
// Map UID and set UID to 1000.
// Mount the host's user code directory (which is on the host at /tmp/sandbox_xyz) to /app (read-only):
mount("/tmp/sandbox_xyz", "/app", "none", MS_BIND | MS_REC, NULL);
mount("/app", "/app", "none", MS_REMOUNT | MS_RDONLY, NULL); // make it read-only
// Mount a tmpfs at /workspace:
mount("tmpfs", "/workspace", "tmpfs", 0, NULL);
// Then mount the rootfs at / (read-only):
mount(rootfs_path, "/", "ext4", MS_REC | MS_SLAVE, NULL); // but we are using a different filesystem type? Actually, the rootfs might be an ext4 image? Or we can use a directory that is the rootfs.
// Then set the working directory to /workspace.
// Then set the hostname.
// Then set seccomp.
// Then set ulimit.
// Then exec the command: e.g., python3 /app/script.py
But note: the rootfs must contain the necessary libraries and the python3 binary? We can have a minimal rootfs that has python3 and the standard library.
And we have to set the PATH? We can set the environment.
Also, the user code might need network? We can choose to not set up any network, so the network namespace will have no interfaces.
And we set the seccomp filter to allow only the necessary syscalls for python3 and the standard library.
This seems feasible.
But note: the rootfs we mount at / must be read-only, and we have /app (read-only) and /workspace (writable) as separate mounts.
We also have to set the /tmp to a tmpfs? We already have /workspace as tmpfs, but we can also mount a tmpfs at /tmp (with mode 1777) for temporary files that the user code might create.
So:
mount("tmpfs", "/tmp", "tmpfs", 0, "mode=1777");
Then we have:
/: rootfs (read-only)
/app: user code (read-only)
/workspace: writable tmpfs (owned by 1000:1000)
/tmp: writable tmpfs (mode 1777)
And we set the working directory to /workspace.
Then the user code runs with UID 1000, with no capabilities, with a seccomp filter, and with resource limits.
This is a basic design.
However, we must also consider:
- The user code might try to break out by using the mount namespace? But we are the only one in the mount namespace and we have mounted the rootfs as read-only and we have no write access to the host's mount points (except the ones we explicitly mounted, like the host's user code directory, which is read-only).
- The user code might try to access /proc or /sys? We can mount proc and sysfs? But we don't want to. We can leave them unmounted, then /proc and /sys are not available? Actually, they are available in the rootfs? If the rootfs has /proc and /sys, then they are there. But if we don't mount them, then they are empty? Actually, if the rootfs has /proc and /sys, then they are directories. But if we don't mount procfs and sysfs on them, then they are just empty directories? But the kernel provides /proc and /sys as virtual filesystems, so if we don't mount them, then the directories in the rootfs are just empty directories.
So we can avoid mounting proc and sysfs.
- The user code might try to open /dev/null? We can have /dev in the rootfs with the necessary devices? Or we can mount a devtmpfs? But we don't want to give too much access.
We can have a minimal /dev in the rootfs with only null, zero, etc.
- The user code might try to fork bomb? We have set nproc ulimit and also the PID namespace will limit the number of processes? The PID namespace will have only one process (the user code and its children) but we can set the maximum number of processes in the cgroup? Actually, we set the cgroup for the process and then the children are in the same cgroup, and we can set the pids.max in the cgroup.
We can set in the cgroup:
echo 10 > pids.max
to limit to 10 processes.
- The user code might try to use too much memory? We set memory.max in the cgroup.
- The user code might try to use too much CPU? We set cpu.max in the cgroup.
- The user code might try to write to disk? We have the rootfs read-only, and the only writable are /workspace and /tmp (which are tmpfs). So no disk writes? But tmpfs uses memory and swap? We set memory limit, so that will limit the tmpfs.
- The user code might try to create a huge file in /workspace? The memory limit will limit that because tmpfs uses memory.
So we are safe.
Now, the seccomp filter: we need to allow the syscalls that python3 and the standard library use. This is language-specific. We can generate a seccomp filter by running the code in a safe environment and tracing the syscalls? Or we can use a predefined set.
For example, for a simple Python script, we might need:
read, write, open, close, fstat, mmap, mprotect, munmap, brk, access, pipe, select, epoll, wait4, getpid, getuid, getgid, geteuid, getegid, getppid, kill, lseek, stat, fstat, times, uname, sysinfo, getrandom, clock_gettime, etc.
But we must deny:
- Any syscall that can modify the system (like mount, umount, ptrace, etc.)
- Any syscall that can access the network (if we don't allow network) like socket, connect, etc.
We can start with a default deny and then allow the necessary ones.
We can use libseccomp to build the filter.
Steps for seccomp:
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL); // default kill
// Then allow the necessary syscalls.
// Example for read, write, open, close, etc.
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 0);
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0);
...
// Then load the filter.
But note: the user code might be in a different language, so we need a different set.
We can have a set of filters for each language/runtime.
Alternatively, we can run the user code in a VM (like gVisor) that already provides a secure environment and we don't have to worry about the syscalls? But the problem says "create", so we are expected to design.
Given the complexity of the seccomp filter, we might want to use a tool that generates it automatically (like syscall-seccomp).
But for the design, we can say:
The policy includes a seccomp filter that is generated for the specific runtime (e.g., Python, Node.js, etc.) and only allows the syscalls that are necessary for that runtime and the standard library.
And we also have the file system policy: only /, /app, /workspace, /tmp are available, and /app is read-only, /workspace and /tmp are writable.
And we have the resource limits in the cgroup.
And we have the user namespace and the other namespaces.
This should be safe.
However, note that there might be vulnerabilities in the kernel that could allow escape. So we must keep the kernel updated and use the latest security features.
Also, we are using a minimal rootfs to reduce the attack surface.
Now, the implementation in code:
We can write a C program that does:
int main(int argc, char *argv[]) {
// Step 0: Parse arguments: the command to run (with arguments) and the path to the user code on the host.
// Step 1: Create a cgroup (or use a pre-created one) and set the limits.
// Step 2: fork.
// Step 3: In the parent:
// write child's PID to cgroup.procs.
// wait for child.
// Step 4: In the child:
// unshare namespaces.
// set up user namespace (map UID 1000 to 1000, set UID to 1000).
// mount the host's user code directory to /app (read-only).
// mount tmpfs at /workspace and /tmp.
// mount the rootfs at /.
// set the hostname.
// set seccomp filter.
// set ulimit.
// chdir to /workspace.
// exec the command.
}
But note: we are running as root, and we are going to set up the mount namespace and mount the rootfs. We have to have the rootfs available.
We can have a pre-built rootfs in a directory (say /var/lib/sandbox/rootfs) that is read-only.
And we have to copy the user code to a host directory (say /tmp/sandbox_xyz) before we start the sandbox? Actually, we can have the user code in a directory that we pass as an argument.
But note: the user code might be a single file or a directory. We can require the user code to be in a directory.
And we have to set the command to run (e.g., "python3 script.py") and then we run that command in the sandbox.
We also have to set the environment? We can set a minimal environment (PATH, etc.).
This is a high-level design.
There are many details to consider, but this should be a good starting point.
However, note that the user code might be in a compiled language and we might need to run a binary. Then we have to make sure the rootfs has the necessary dynamic libraries.
We can use a tool like ldd to find the libraries and then copy them to the rootfs? But we are using a pre-built rootfs that already contains the common libraries.
Alternatively, we can use a static binary? Then we don't need the libraries.
But for interpreted languages, we need the interpreter and the standard library.
We can have multiple rootfs for different languages.
Or we can have a rootfs that includes multiple interpreters.
Given the complexity, we might want to use a container image (like Docker) and then run it with very restrictive flags? But then we are not creating from scratch.
Since the problem says "create", we are expected to design a system, and we have designed one using Linux namespaces, cgroups, seccomp, and a minimal rootfs.
We can also consider using existing tools like bubblewrap (bwrap) which does similar things, but again, we are creating.
So the answer is:
We design a sandbox that uses:
- Linux namespaces (user, pid, net, mnt, uts, ipc) for isolation.
- cgroups for resource limits (CPU, memory, pids, and optionally I/O and network).
- seccomp to filter syscalls.
- A minimal rootfs that contains only the necessary runtime and libraries.
- The user code is bind-mounted (read-only) from the host and the sandbox has a writable tmpfs for temporary files.
The sandbox runs the user code as an unprivileged user (with a fixed UID/GID) and with no capabilities.
The policy is defined by:
- The seccomp filter (which syscalls are allowed).
- The file system layout (what is mounted and with what permissions).
- The resource limits (in the cgroup and ulimit).
This design should be safe against a malicious user code, provided the kernel is secure and the seccomp filter is correct.
However, note that writing a correct seccomp filter is hard and we might miss some syscalls. We can use a tool to generate it by tracing the execution of a sample program.
Also, we must ensure that the rootfs is minimal and does not contain any setuid binaries or unnecessary daemons.
And we must keep the kernel and the sandbox manager updated.
This is a complex system and we have only outlined the design.
For a production system, we would use a well-audited sandboxing solution (like gVisor, Firecracker, or even Docker with an appropriate seccomp profile and user namespace).
But for the purpose of this problem, we have designed a sandbox using Linux primitives.
Note: This design requires the sandbox manager to run as root.
If we want to avoid running as root, we can use user namespaces and cgroup delegation, but that is even more complex.
We can also consider using a VM (like KVM) to run the user code, but that is heavier.
Given the requirements (isolation, resource caps, policy), our design meets them.
Let me summarize:
Isolation: achieved by namespaces (the process is isolated from the host and other processes).
Resource caps: achieved by cgroups and ulimit.
Policy: achieved by seccomp and file system layout.
We have described a way to set up the sandbox.
Now, we can write a sample code (in C) that sets up such a sandbox, but note that it would be long and complex.
Since the problem says "create", and we are in a text-based environment, we provide the design.
If we were to implement, we would write a C program that uses:
- unshare, setns, mount, pivot_root (or just mount and then chroot? but pivot_root is safer because we can have the old root mounted somewhere and then unmount it).
- prctl for seccomp.
- setrlimit for ulimit.
- and the cgroup operations (by writing to cgroup.procs and cgroup.force).
But note: we are using cgroup v2, which has a unified hierarchy.
We can mount cgroup2 at /sys/fs/cgroup and then create a directory for our sandbox.
Steps for cgroup:
mount("cgroup2", "/sys/fs/cgroup", "cgroup2", 0, NULL);
mkdir("/sys/fs/cgroup/sandbox_xyz");
write to "/sys/fs/cgroup/sandbox_xyz/cgroup.controllers" to enable the controllers we want (cpu, memory, pids, etc.)
write to "/sys/fs/cgroup/sandbox_xyz/cpu.max" for CPU limit.
write to "/sys/fs/cgroup/sandbox_xyz/memory.max" for memory limit.
write to "/sys/fs/cgroup/sandbox_xyz/pids.max" for process limit.
Then after fork, write the child's PID to "/sys/fs/cgroup/sandbox_xyz/cgroup.procs".
But note: the child might be in a different PID namespace? The PID we write is the PID in the parent's PID namespace? Actually, the cgroup.procs file expects the PID in the caller's PID namespace? And we are in the parent's PID namespace? So we write the child's PID (as seen by the parent) and then the child (and its children) will be in the cgroup.
This should work.
Given the complexity, we leave the implementation as an exercise.
But note: the sandbox manager must run as root and must be careful about the operations it performs.
We must also clean up the cgroup and the mounted filesystems after the child exits.
This design is for Linux only.
For other operating systems, we would need a different approach.
Given the problem does not specify the OS, we assume Linux.
This is a safe sandbox design for untrusted user code on Linux.
I'll design a comprehensive sandbox system for untrusted user code execution with multiple layers of defense. This is a reference architecture - actual implementation requires careful engineering and security review.
Multi-Layer Sandbox Architecture
Layer 1: Process Isolation
# Use Linux namespaces (unshare):
- PID namespace: Isolate process tree
- Network namespace: Isolate network stack
- Mount namespace: Restrict filesystem view
- UTS namespace: Isolate hostname
- IPC namespace: Isolate inter-process communication
- User namespace: Map to unprivileged UID/GID
Layer 2: Resource Control (cgroups v2)
# Create cgroup with strict limits:
/sys/fs/cgroup/sandbox-<id>/
├── cpu.max # "10000 100000" (10% of 1 CPU)
├── memory.max # "100M" (hard limit)
├── memory.high # "80M" (soft limit, triggers reclaim)
├── io.max # "8:0 rbps=1M wbps=1M" (disk I/O limits)
├── pids.max # "50" (max processes)
└── rdma.current # Disable RDMA if not needed
Layer 3: Syscall Filtering (seccomp-bpf)
// Default-deny policy with explicit allowlist
struct sock_filter filter[] = {
// Allow essential syscalls only
BPF_STMT(BPF_LD|BPF_W|BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_read, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_write, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_open, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_fstat, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_mmap, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_mprotect, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_munmap, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_brk, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_rt_sigaction, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_rt_sigprocmask, 0, 1),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_exit, 0, 1),
// Deny everything else
BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL_PROCESS),
};
Layer 4: Filesystem Restrictions
# Read-only rootfs with minimal packages
/
├── bin/ # Only essential binaries (ls, cat, bash if needed)
├── lib/ # Minimal libc, language runtime libs only
├── usr/
│ ├── bin/ # Language runtime (python3, node, etc.)
│ └── lib/ # Language standard library
└── tmp/ # tmpfs mounted read-write, size-limited
# Bind mounts:
- /sandbox/app # User code (read-only)
- /sandbox/data # Input data (read-only)
- /sandbox/output # Writable output directory
Layer 5: Network Policy
# Option A: No networking (default)
ip netns exec <sandbox> true # No interfaces
# Option B: Restricted network (if needed)
- Create veth pair: veth-host <-> veth-sandbox
- Apply tc qdisc to limit bandwidth:
tc qdisc add dev veth-host root tbf rate 1mbit burst 32kbit latency 400ms
- Use eBPF/XDP for deep packet inspection
- Block all except specific destinations/ports
Layer 6: Time & Signal Limits
# Set RLIMITs:
- RLIMIT_CPU: 5 seconds (wall time)
- RLIMIT_AS: 200M (virtual memory)
- RLIMIT_FSIZE: 10M (max file size)
- RLIMIT_NPROC: 32 (max processes)
- RLIMIT_NOFILE: 64 (max file descriptors)
Layer 7: Capability Dropping
// Drop all capabilities in user namespace
cap_t caps = cap_init();
cap_set_flag(caps, CAP_EFFECTIVE, 0, NULL, CAP_CLEAR);
cap_set_flag(caps, CAP_PERMITTED, 0, NULL, CAP_CLEAR);
cap_set_proc(caps);
cap_free(caps);
// Explicitly keep only if absolutely needed:
// CAP_NET_BIND_SERVICE (if binding to low ports)
// CAP_SYS_CHROOT (if we use chroot instead of pivot_root)
Layer 8: Language-Specific Sandboxing
# For Python: Use restricted execution mode
import sys
from RestrictedPython import compile_restricted
from RestrictedPython import safe_builtins
# For Node.js: Use vm2 with hardened options
const vm = require('vm2').VM;
const vm = new vm({
timeout: 2000,
sandbox: { /* minimal global */ },
eval: false,
wasm: false
});
# For WASM: Use wasmtime/wasi with explicit capabilities
wasmtime run \
--invoke main \
--dir .:ro \
--dir output:rw \
--max-memory=100M \
program.wasm
Implementation Blueprint
#!/usr/bin/env python3
"""
Sandbox Orchestrator - Coordinates all layers
"""
import os
import sys
import json
import subprocess
import ctypes
import tempfile
from pathlib import Path
class Sandbox:
def __init__(self, config):
self.config = config
self.cgroup_path = None
self.pid = None
def prepare_rootfs(self):
"""Create minimal rootfs using debootstrap or custom"""
# Use distrobox or create from scratch
pass
def create_cgroup(self):
"""Set up cgroup v2 with limits"""
cg_path = f"/sys/fs/cgroup/sandbox-{os.getpid()}"
os.makedirs(cg_path, exist_ok=True)
with open(f"{cg_path}/cgroup.controllers", "w") as f:
f.write("cpu memory pids io\n")
# Set limits
with open(f"{cg_path}/cpu.max", "w") as f:
f.write(f"{self.config['cpu_quota']} 100000\n")
with open(f"{cg_path}/memory.max", "w") as f:
f.write(f"{self.config['memory_limit']}\n")
with open(f"{cg_path}/pids.max", "w") as f:
f.write(str(self.config['max_processes']))
self.cgroup_path = cg_path
def apply_seccomp(self):
"""Load BPF filter (requires libseccomp)"""
# Load precompiled filter for language runtime
pass
def setup_namespaces(self):
"""Unshare namespaces via clone() or unshare()"""
# Use CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS | ...
pass
def run(self, command, code_path):
"""Execute untrusted code"""
# 1. Copy code to isolated directory
# 2. Set up mount namespace with rootfs
# 3. Apply seccomp
# 4. Join cgroup
# 5. Execute command
# Pivot to new root
# pivot_root(new_root, old_root)
# Drop privileges
# setuid(1000); setgid(1000)
# Execute
os.execvp(command[0], command)
Security Considerations & Gotchas
- Kernel Exploits: Even with namespaces, kernel vulnerabilities can break isolation. Keep kernel patched.
- Side Channels: Cache timing attacks, speculative execution (Spectre/Meltdown) - consider CPU pinning and cache flushing.
- Resource Exhaustion: Ensure cgroup enforcement works (memory + OOM killer).
- File Descriptor Leakage: Close all FDs before exec (use
close_range()).
- Docker Escape: If using containers, ensure container runtime is locked down.
- Time-of-Check-Time-of-Use: Race conditions in path handling.
- Seccomp Bypass: Some syscalls can be invoked via
syscall() or iretq - use SECCOMP_RET_TRAP with signal handler for analysis.
- Filesystem: Avoid
pivot_root if possible - use chroot + mount --make-rprivate /.
- Signal Handling: Ignore or block all signals except
SIGKILL.
- Audit: Log all syscalls that are denied for tuning.
Production Recommendations
-
Use existing solutions first:
- gVisor: User-space kernel, excellent isolation
- Firecracker: MicroVMs, near-native performance
- Kata Containers: Lightweight VMs
- Docker with AppArmor/SELinux: Good for less hostile code
-
Defense in depth:
Untrusted Code
↓
Language-level sandbox (vm2, RestrictedPython)
↓
Seccomp + Capability dropping
↓
User + PID + Mount namespaces
↓
cgroups (resource limits)
↓
Networking isolation (ebpf/iptables)
↓
Optional: Lightweight VM (KVM/Firecracker)
-
Monitoring & Logging:
- Audit all syscalls (
auditd)
- Track cgroup metrics
- Log seccomp violations
- Resource usage telemetry
-
Testing:
- Use
nsjail or bubblewrap for quick testing
- Run escape tools:
s sandbox, pwnkit, cve-2022-0492 tests
- Fuzz the sandbox interface
Example Policy Configuration
{
"language": "python",
"timeout": 5,
"memory_mb": 100,
"cpu_percent": 10,
"max processes": 32,
"max_files": 64,
"network": "none",
"allowed_paths": [
"/sandbox/app",
"/sandbox/data"
],
"allowed_syscalls": [
"read", "write", "open", "close", "fstat",
"mmap", "mprotect", "munmap", "brk",
"rt_sigaction", "rt_sigprocmask", "exit"
],
"env_vars": {
"PATH": "/usr/bin:/bin",
"LANG": "C.UTF-8"
}
}
Critical Warnings
⚠️ This is extremely hard to get right. Even Google's V8 sandbox has had escapes. Consider:
-
Commercial solutions:
- Nabla (by Google)
- Firejail (for desktop apps)
- AWS Lamba / GCP Cloud Functions (managed isolation)
-
If building yourself:
- Start with
nsjail or firejail and customize
- Regularly update to latest kernel
- Assume breach - design for detection/containment
- Use hardware virtualization (AMD-V/SVM) for highest security
-
Never trust:
- User-provided filenames (path traversal)
- Environment variables (injection)
- Resource usage predictions (always enforce)
Remember: No sandbox is 100% secure against a determined adversary with kernel 0-day. For critical applications, use air-gapped systems or dedicated hardware security modules.
Would you like me to elaborate on any specific layer or provide concrete implementation examples for a particular language/runtime?