Can CubeSandbox Run Arbitrary Code? A Deep Dive into Secure Execution

Yes, CubeSandbox can run arbitrary code inside hardware-isolated micro-VMs, but strict security policies prevent access to the host system, network, and secrets.

TencentCloud/CubeSandbox provides a secure, hardware-level isolated environment where user-supplied code executes within a lightweight virtual machine. While the platform supports running arbitrary code in languages like Python, Node.js, and Bash, it enforces rigorous containment through KVM-based virtualization and configurable policy constraints.

How CubeSandbox Executes Arbitrary Code

The core execution path flows through the Sandbox.run_code method, which transmits code to a sandbox instance via the /execute HTTP endpoint and streams back results as an Execution object.

The Execution Flow in Python SDK

In sdk/python/cubesandbox/sandbox.py (lines 33-45), the run_code method handles the entire lifecycle:

  1. Sends code payload to the sandbox's envd process
  2. Streams NDJSON responses from the execution environment
  3. Populates an Execution model with results, logs, and errors

Because the sandbox runs a full guest OS built on RustVMM + KVM, any code interpretable by the installed runtimes can execute. The VM architecture ensures that arbitrary code runs in its own kernel and memory space, preventing container-level escapes.

The Execution Model

Results are encapsulated in the Execution model defined in sdk/python/cubesandbox/_models.py (lines 166-182). This object contains:

  • text: Final output from the code execution
  • logs: Runtime logging information
  • error: Error details if execution fails

Security Mechanisms That Isolate Arbitrary Code

CubeSandbox implements multiple defense layers to ensure arbitrary code cannot compromise the host or exfiltrate data.

Hardware-Level Isolation

Each sandbox instance operates as a KVM-based micro-VM orchestrated by the CubeSandbox service. The implementation in CubeNet/cubevs/* provides true hardware isolation where each execution environment receives its own kernel and dedicated memory space, eliminating shared-kernel vulnerabilities common to container-based sandboxes.

Resource Limits and Timeouts

Resource consumption is strictly controlled through configurable parameters:

  • Sandbox.create(..., timeout=...): Sets maximum execution duration
  • Sandbox.set_timeout: Adjusts limits dynamically during runtime

These constraints prevent runaway processes from exhausting host resources.

Network Egress Control

Outbound connections are blocked by default and can only be enabled via explicit whitelist policies. Network restrictions are managed through sandbox._policy configurations, ensuring arbitrary code cannot initiate unauthorized external connections or exfiltrate data.

Credential Vault Protection

Secrets are never injected into the sandbox process directly. Instead, the security proxy (documented in docs/guide/security-proxy.md) mediates all credential access, ensuring that arbitrary code cannot retrieve API keys, passwords, or other sensitive material even if it attempts to read environment variables or files.

Snapshot and Rollback

The CubeCoW copy-on-write snapshot engine enables instant state capture and restoration. If arbitrary code misbehaves or corrupts the environment, the system can revert to a clean state immediately, limiting the blast radius of any malicious or buggy code.

Code Examples: Running Arbitrary Code in CubeSandbox

Python SDK: Basic Execution

Create a sandbox and execute a Python expression:

from cubesandbox import Sandbox

# Create a sandbox using the default Python template

with Sandbox.create() as sb:
    # Execute arbitrary Python code

    exec_res = sb.run_code("x = 1\nx + 42")
    print(exec_res.text)  # → "43"

The Sandbox.create() method launches a fresh VM instance, while run_code streams output and returns the Execution object containing the final result.

Python SDK: Streaming Output with Callbacks

Capture real-time stdout and stderr for monitoring long-running arbitrary code:

from cubesandbox import Sandbox, OutputMessage, Result

def on_stdout(msg: OutputMessage):
    print("[STDOUT]", msg.text)

def on_stderr(msg: OutputMessage):
    print("[STDERR]", msg.text)

def on_result(res: Result):
    print("[RESULT]", res.text)

with Sandbox.create() as sb:
    sb.run_code(
        code="""
import sys
print("hello")
sys.stderr.write("oops\\n")
1 + 2
""",
        on_stdout=on_stdout,
        on_stderr=on_stderr,
        on_result=on_result,
    )

Node.js SDK: Equivalent Implementation

The Node.js implementation provides identical functionality:

import { Sandbox } from "cubesandbox";

(async () => {
  const sb = await Sandbox.create();
  const exec = await sb.runCode(`console.log("hi"); 5 + 7`);
  console.log(exec.text); // "12"
})();

The TypeScript implementation in sdk/node/src/sandbox.ts (lines 447-459) mirrors the Python SDK's streaming architecture, ensuring consistent behavior across language bindings.

Summary

  • CubeSandbox can execute arbitrary code within supported language runtimes (Python, Node.js, Bash) through the Sandbox.run_code method.
  • Hardware isolation via RustVMM and KVM prevents escape from the guest VM into the host system.
  • Resource constraints including CPU, memory, and execution timeouts are configurable per sandbox instance.
  • Network egress is denied by default, with whitelist policies controlling outbound access.
  • Secrets are proxied through a security vault, never exposed directly to the sandbox environment.
  • CubeCoW snapshots enable instant rollback if arbitrary code compromises the environment.

Frequently Asked Questions

Is CubeSandbox safe for running untrusted code?

Yes, CubeSandbox is designed specifically for untrusted code execution. The combination of KVM-based hardware isolation, network blocking by default, and the credential vault architecture ensures that arbitrary code cannot access the host filesystem, network resources, or sensitive secrets. The CubeNet/cubevs/* implementation provides stronger isolation than container-based alternatives.

What programming languages does CubeSandbox support?

CubeSandbox supports any language runtime installed in the guest VM template, including Python, Node.js, and Bash. The run_code method in sdk/python/cubesandbox/sandbox.py and its Node.js equivalent in sdk/node/src/sandbox.ts transmit code as text to the sandbox environment, where the appropriate interpreter executes it.

How does CubeSandbox prevent network-based attacks?

By default, all outbound network connections are blocked. Network egress must be explicitly enabled through policy configurations in sandbox._policy. This architecture, detailed in docs/guide/security-proxy.md, ensures that arbitrary code cannot establish connections to external services, preventing data exfiltration and command-and-control communications.

Can CubeSandbox access host system files?

No. The sandbox runs as a micro-VM with its own kernel and memory space, completely isolated from the host filesystem. According to the architecture overview in docs/architecture/overview.md, the RustVMM + KVM implementation ensures that even privileged operations inside the guest cannot escape to the host system.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →