0Pricing
AI Agents · 课时

高安全性代码智能体的 VM 隔离

gVisor、Firecracker microVMs 和面向智能体的硬件级隔离

高安全性代码智能体的 VM 隔离 是 CoddyKit 上的免费 AI Agents 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。

超越 Docker:更强的隔离

标准 Docker 容器共享主机内核。容器内的内核漏洞可能让攻击者逃逸到主机。对于高安全性的代码执行,需要更强的隔离层。

两种主要方案是:gVisor(用户空间内核代理)和 Firecracker(轻量级 microVMs)。

gVisor 的工作原理

gVisor 在容器和主机内核之间插入一个名为 Sentry 的用户空间组件。容器的系统调用会发送到 Sentry,由它使用 Go 重新实现一个安全的子集,而不是真正的内核。

该运行时称为 runsc(运行沙盒化容器)。

# Configure Docker to use gVisor runtime (runsc)
# /etc/docker/daemon.json:
# {
#   "runtimes": {
#     "runsc": { "path": "/usr/local/bin/runsc" }
#   }
# }

import docker
client = docker.from_env()

output = client.containers.run(
    'python:3.12-slim',
    'python -c "print(\"hello from gVisor\")"',
    runtime='runsc',          # use gVisor
    network_disabled=True,
    auto_remove=True
)
print(output.decode())

gVisor 系统调用拦截

当容器内的代码调用 open()、read() 或 socket() 时,gVisor 会拦截系统调用,并决定允许、模拟还是拒绝该调用。

默认情况下,ptrace 等敏感系统调用以及创建原始套接字的操作会被阻止,从而堵住常见的攻击路径。

# gVisor blocks dangerous syscalls like ptrace.
# This code would fail inside a gVisor container:
#
# import ctypes
# libc = ctypes.CDLL(None)
# libc.ptrace(...)   # EPERM: Operation not permitted
#
# Normal Python I/O and computation works fine:
# open(), read(), write(), socket() (if network enabled)
# are all emulated safely by Sentry.
print('gVisor intercepts syscalls before they reach the host kernel')

gVisor 的性能权衡

每个系统调用都会经过 Sentry,而不是直接发送到内核。这会使 I/O 密集型工作负载增加约 10% 到 30% 的开销。对于 CPU 密集型计算,开销要小得多。

启动时间与常规 Docker 相近,仅需几毫秒。

import time
import docker

client = docker.from_env()

start = time.time()
client.containers.run('python:3.12-slim', 'python -c "pass"',
                      runtime='runsc', auto_remove=True)
print(f'gVisor startup: {time.time()-start:.2f}s')   # ~0.3-0.8s

start = time.time()
client.containers.run('python:3.12-slim', 'python -c "pass"',
                      auto_remove=True)
print(f'Docker startup: {time.time()-start:.2f}s')   # ~0.1-0.3s

Firecracker microVMs

Firecracker 采用完全不同的方法:让每个工作负载运行在拥有独立内核的完整虚拟机中。VM 的启动时间约为 50 毫秒,额外内存开销仅约 5 MB。

由于 VM 拥有完全独立的内核,因此不存在共享内核攻击面。

# Firecracker is controlled via a REST API on a Unix socket.
# Python SDK example (firecracker-python-sdk or direct HTTP):

import requests_unixsocket

session = requests_unixsocket.Session()
base = 'http+unix://%2Ftmp%2Ffirecracker.socket'

# Boot the microVM
session.put(f'{base}/boot-source', json={
    'kernel_image_path': '/opt/kernel/vmlinux',
    'boot_args': 'console=ttyS0 reboot=k panic=1 pci=off'
})
session.put(f'{base}/actions', json={'action_type': 'InstanceStart'})
print('MicroVM booted in ~50ms')

Firecracker 安全模型

Firecracker VM 从设计上就具备最小化的攻击面。VMM 只公开 5 种设备类型(virtio-net、virtio-block、串行设备、RTC、键盘)。没有 USB、PCI 总线或 BIOS。

每个 VM 都在虚拟机监控程序层面隔离——VM 内的内核漏洞无法触及主机。

# Firecracker security properties:
# 1. Each microVM has its own Linux kernel instance
# 2. Guest-to-host attack surface is tiny (5 device types)
# 3. The VMM (Virtual Machine Monitor) runs unprivileged
# 4. No shared memory between VMs
# 5. Snapshot/restore: freeze a running VM, clone it for next request

# Used in production by:
# - AWS Lambda (each function invocation = Firecracker microVM)
# - Fly.io (each app container)
# - Replit (code execution)
print('Firecracker: full VM isolation at container startup speed')

Kata Containers:兼顾两者

Kata Containers 使用轻量级 VM(可以使用 Firecracker 或 QEMU),但公开标准的 OCI 容器接口。您可以运行普通的 Docker 命令;Kata 会透明地处理 VM 层。

import docker
client = docker.from_env()

# Kata Containers registered as 'kata-runtime' in daemon.json
output = client.containers.run(
    'python:3.12-slim',
    'python -c "import platform; print(platform.node())"',
    runtime='kata-runtime',   # each container = a VM
    mem_limit='256m',
    network_disabled=True,
    auto_remove=True
)
print(output.decode())  # unique VM hostname

选择合适的隔离级别

合适的沙盒取决于您的威胁模型和延迟预算:

  • Docker (runc):速度快、开销低、共享内核——适合可信或经过轻度过滤的代码
  • gVisor (runsc):过滤系统调用、使用相同的镜像格式、开销适中——在两者之间取得良好平衡
  • Firecracker/Kata:完整的 VM 隔离、启动时间为 50 毫秒——适合大规模运行不可信的用户代码

安全性与启动延迟对照表

隔离深度与启动速度成反比。请根据代理用例可接受的延迟进行选择。

# Isolation vs Latency summary:
#
# Runtime          | Isolation     | Startup  | Overhead
# -----------------|---------------|----------|----------
# runc (Docker)    | Namespace      | ~100ms   | ~0%
# gVisor (runsc)   | Syscall filter | ~300ms   | ~15-30%
# Kata Containers  | Full VM        | ~500ms   | ~10%
# Firecracker      | Full VM        | ~50ms    | ~5%
# QEMU KVM         | Full VM        | ~1-2s    | ~5%
#
# For interactive agent tools: gVisor is usually the sweet spot.
# For high-throughput batch jobs: Firecracker snapshots.

ISOLATION_OPTIONS = {
    'runc (Docker)':   {'isolation': 'Namespace',      'startup': '~100ms', 'overhead': '~0%'},
    'gVisor (runsc)':  {'isolation': 'Syscall filter',  'startup': '~300ms', 'overhead': '~15-30%'},
    'Kata Containers': {'isolation': 'Full VM',         'startup': '~500ms', 'overhead': '~10%'},
    'Firecracker':     {'isolation': 'Full VM',         'startup': '~50ms',  'overhead': '~5%'},
    'QEMU KVM':         {'isolation': 'Full VM',        'startup': '~1-2s',  'overhead': '~5%'},
}

for runtime, info in ISOLATION_OPTIONS.items():
    print(f"{runtime:<17} | {info['isolation']:<14} | startup {info['startup']:<7} | overhead {info['overhead']}")

预热沙盒

为每个代理请求冷启动 VM 会增加延迟。生产系统会预热一组空闲沙盒。当请求到达时,获取一个已预热的沙盒,使用后将其销毁(绝不重复使用)。

import queue, threading

SANDBOX_POOL_SIZE = 5
pool = queue.Queue()

def pre_warm():
    'Start a sandbox and put it in the pool.'
    container = client.containers.create(
        'python:3.12-slim',
        'tail -f /dev/null',
        runtime='runsc',
        mem_limit='256m',
        network_disabled=True
    )
    container.start()
    pool.put(container)

# Pre-warm the pool at startup
for _ in range(SANDBOX_POOL_SIZE):
    threading.Thread(target=pre_warm, daemon=True).start()

def claim_sandbox():
    return pool.get(timeout=5)  # blocks until one is ready

通过快照和恢复实现扩展

Firecracker 支持将运行中的 VM 快照保存到磁盘。快照会捕获内存状态、设备状态和 CPU 寄存器。通过快照恢复只需约 10 毫秒,比冷启动快得多。

利用这种模式,可以预先初始化一次 Python 解释器,为其创建快照,然后针对每个请求进行恢复。

# Firecracker snapshot workflow:
# 1. Boot microVM, run Python interpreter, wait for REPL ready
# 2. Pause VM
# 3. Create snapshot
#    PUT /snapshot/create { snapshot_path, mem_file_path }
# 4. For each request:
#    PUT /snapshot/load { snapshot_path, mem_file_path }
#    # VM resumes from paused state with Python already loaded
#    # Send code via stdin/virtio-serial, read output
# 5. Discard VM after request (never reuse)

print('Snapshot restore: ~10ms vs 50ms cold boot for Firecracker')

gVisor 在容器与主机内核之间插入了哪个组件?

gVisor 的隔离模型依赖于一个拦截系统调用的特定组件。理解这一架构是评估其安全保障的关键。

VM 隔离回顾

对于高安全性的代理代码执行,应从标准 Docker 转向gVisor(拦截系统调用、开销低)或 Firecracker(完整 VM、启动时间 50 毫秒、额外开销约 5 MB)。

其中的权衡始终是隔离深度与启动延迟。在生产环境中,预热池和 VM 快照可以弥补大部分延迟成本。

常见问题解答

「高安全性代码智能体的 VM 隔离」课时是免费的吗?

是的 — 「高安全性代码智能体的 VM 隔离」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。

「高安全性代码智能体的 VM 隔离」这节课中我会学到什么?

gVisor、Firecracker microVMs 和面向智能体的硬件级隔离 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Agents 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「高安全性代码智能体的 VM 隔离」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Agents 课中编写并运行代码吗?

能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 基于 Docker 的智能体沙箱
  2. 高安全性代码智能体的 VM 隔离
  3. E2B 与云沙箱服务
  4. 代码执行的安全策略
← 返回 AI Agents