fix(sandbox): Docker 文件操作改走沙箱账号,堵住符号链接越权并回收僵尸进程
archive 接口(CopyToContainer / CopyFromContainer / ContainerStatPath)由 daemon 执行,它忽略 exec user 一律以 root 操作,并在解析路径时跟随符号链接。而沙箱账号对 /workspace 有写权限,调用侧的路径守卫(isUnderRoot、cleanSessionInputPath)又都是 字符串前缀比较,于是 `ln -s /root /workspace/output/esc` 之后, /workspace/output/esc/secret.txt 既能通过守卫,又会被 daemon 以 root 读出来。真机 验证过:非特权账号 cat 该路径是 Permission denied,docker cp 同一路径拿到明文。 WriteFile / ReadFile / Stat 改为以 DefaultSandboxExecUser 走 exec,能不能读写交给 内核判定,符号链接指向哪里都不再重要,也不存在「先校验后使用」之间被换掉链接的窗口 (这正是 realpath 预校验方案挡不住的)。Stat 用 find,它不跟随符号链接,因此链接如实 报告为 other 类型,read_sandbox_file 在尝试读取之前就会拒绝。两个 copy 端点从 dockerEngineAPI 接口里移除——留着未使用的入口等于把这一类问题继续敞着。 容器入口是 sleep,从不调用 wait(),后台进程活得比启动它的 exec 久就会变成没人回收的 僵尸,堆到 pids_limit 之后所有 exec 都会失败。补 HostConfig.Init 交给 tini。实测: 三个孤儿进程,不开 Init 留下三个 Z,开了之后为零。 同步订正文档与注释中过时的 root 表述:上一次提交已把 shell_exec 降权到沙箱账号,但 docs 仍写着「exec 默认以 root 运行」「shell_exec 默认就是 root」,并据此把活跃标记可被 无限刷新归因于「容器内 root 信任边界」——标记是 chmod 666,普通技能脚本就能刷新。main
parent
c920a00918
commit
d6ddad5430
|
|
@ -46,7 +46,7 @@ ENTRYPOINT 拼到 Cmd 前面,所以只设 Cmd 时,任何声明了 ENTRYPOINT
|
|||
| `Get` / `List` | `GET /containers/json?filters=label=…`,服务端按 label 过滤 |
|
||||
| `Delete` | `DELETE /containers/{id}?force=1&v=1` |
|
||||
| `Exec` | `POST /containers/{id}/exec` → `/exec/{id}/start`(hijack)→ `/exec/{id}/json` |
|
||||
| `WriteFile` / `ReadFile` / `Stat` | `PUT` / `GET` / `HEAD /containers/{id}/archive` |
|
||||
| `WriteFile` / `ReadFile` / `Stat` | 刻意不用 archive 接口,走 exec 的 `cat > "$1"` / `cat` / `find -maxdepth 0 -printf`(见下) |
|
||||
| `MakeDir` / `Remove` / `ListDir` | 没有原生接口,用 exec 的 `mkdir -p` / `rm -rf` / `find -printf` |
|
||||
|
||||
几个不显然但要紧的决定:
|
||||
|
|
@ -70,15 +70,29 @@ ENTRYPOINT 拼到 Cmd 前面,所以只设 Cmd 时,任何声明了 ENTRYPOINT
|
|||
就能让容器永久免于回收。往前改只会让自己更早被回收,不构成问题。此外清扫在真正删除前
|
||||
会再读一次标记:列举加逐个 stat 在繁忙 daemon 上不是瞬时的,期间会话可能已被恢复。
|
||||
|
||||
残留风险:容器内以 root 跑的东西(`shell_exec` 默认就是 root)可以起一个后台循环持续
|
||||
`touch` 标记,从而把自己维持成「一直活跃」。这与「容器内 root 能让自己一直运行」是同一
|
||||
信任边界,需要硬上限时应由部署方在 daemon 侧限制。
|
||||
残留风险:标记对沙箱账号可写是刻意的(只跑脚本的会话也要能刷新它),所以任何能在容器里
|
||||
执行命令的东西——包括普通技能脚本,不需要 root——都可以起一个后台循环持续 `touch` 标记,
|
||||
把自己维持成「一直活跃」。当前没有硬寿命上限,需要的话应由部署方在 daemon 侧限制。
|
||||
|
||||
**exec 默认以 root 运行,脚本以 `user`(uid 1000) 运行。** 与 envd 后端的口径一致:
|
||||
`RemoteExecRequest.User` 为空表示 root,脚本执行路径显式传 `DefaultSandboxExecUser`。
|
||||
**所有 exec 都以 `user`(uid 1000) 运行。** 脚本执行、`shell_exec`、以及全部文件操作都显式
|
||||
传 `DefaultSandboxExecUser`。唯一的例外是 manager 自己的 bootstrap:它要把产物目录 `chown`
|
||||
**给**沙箱账号,因此不能以该账号执行,这也是 `RemoteExecRequest.User` 留空的唯一用途。
|
||||
容器 `CapDrop: ALL` 之后额外补回 CHOWN/DAC_OVERRIDE/FOWNER/FSETID/SETGID/SETUID/KILL,
|
||||
这是 root 装包和修属主需要的最小集合;Docker 默认给的 NET_RAW、MKNOD、SYS_CHROOT 等一律不给。
|
||||
|
||||
**文件操作走 exec,不走 archive 接口。** archive 接口(`PUT`/`GET`/`HEAD /archive`)由 daemon
|
||||
执行,这意味着两件事同时成立:它忽略 exec user 一律以 root 操作,并且会在路径解析时跟随符号
|
||||
链接。沙箱账号对 `/workspace` 有写权限,而调用侧的路径守卫都是字符串前缀比较,于是
|
||||
`ln -s /root /workspace/output/esc` 之后,`/workspace/output/esc/secret.txt` 既能通过守卫,
|
||||
又会被 daemon 以 root 读出来(真机验证过,不是推演)。改成以沙箱账号 exec 之后,能不能读写
|
||||
由内核判定,符号链接指向哪里都不再重要,也不存在「先校验后使用」之间被换掉链接的窗口。
|
||||
`Stat` 用 `find`,它不跟随符号链接,因此链接会如实报告为 `other` 类型,要求正规文件的调用方
|
||||
在尝试读取之前就会拒绝。archive 接口里只剩 `HEAD` 还在用,且仅用于读固定路径的活跃标记。
|
||||
|
||||
**PID 1 开 tini(`HostConfig.Init`)。** 容器入口是 `sleep`,它从不调用 `wait()`。长会话里
|
||||
后台进程一旦活得比启动它的 exec 久,退出后就会变成没人回收的僵尸,堆到 `pids_limit` 之后所有
|
||||
后续 exec 都会失败。
|
||||
|
||||
**镜像即模板。** `ListTemplates` 列出 daemon 上带 `com.weknora.sandbox.template=true` 标签的、
|
||||
或名字就是标准镜像的镜像;`EnsureStandardTemplate` 在后台拉取,拉取期间模板状态显示为
|
||||
`building`,与其它后端的模板构建流程对齐。
|
||||
|
|
|
|||
|
|
@ -188,6 +188,19 @@ func (t *ReadSandboxFileTool) Execute(ctx context.Context, args json.RawMessage)
|
|||
Error: fmt.Sprintf("path is a directory, not a file: %s", clean),
|
||||
}, nil
|
||||
}
|
||||
// The directory guard above is a string prefix test, so it cannot tell that
|
||||
// a symlink under the output directory points somewhere else entirely. The
|
||||
// backends report a link as-is rather than as its target, which makes this
|
||||
// the check that keeps such a path from being read at all.
|
||||
if stat.Type != sandbox.RemoteEntryFile {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf(
|
||||
"path is not a regular file: %s; only files produced under %s can be read",
|
||||
clean, rootDir,
|
||||
),
|
||||
}, nil
|
||||
}
|
||||
if stat.Size > maxBytes {
|
||||
logger.Infof(ctx, "[Tool][ReadSandboxFile] refused oversize file: session=%s path=%s size=%d limit=%d",
|
||||
sessionID, clean, stat.Size, maxBytes)
|
||||
|
|
|
|||
|
|
@ -80,6 +80,31 @@ func TestReadSandboxFileReturnsSmallTextOnlyInOutput(t *testing.T) {
|
|||
assert.False(t, duplicated)
|
||||
}
|
||||
|
||||
// The output-directory guard is a string prefix test, so a symlink planted
|
||||
// under that directory satisfies it while pointing anywhere. The backends
|
||||
// report a link as-is instead of following it, and this is the check that
|
||||
// turns that into a refusal before any read is attempted.
|
||||
func TestReadSandboxFileRefusesNonRegularFile(t *testing.T) {
|
||||
source := &fakeSandboxFileSource{
|
||||
stat: &sandbox.RemoteStatEntry{
|
||||
Path: "/workspace/output/esc",
|
||||
Type: sandbox.RemoteEntryOther,
|
||||
Size: 4,
|
||||
},
|
||||
data: []byte("must not be read"),
|
||||
}
|
||||
|
||||
result, err := NewReadSandboxFileTool(source).Execute(
|
||||
sandboxFileTestContext(),
|
||||
json.RawMessage(`{"path":"/workspace/output/esc/secret.txt"}`),
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.False(t, result.Success)
|
||||
assert.Zero(t, source.readCalls, "a non-regular path must never be downloaded")
|
||||
assert.Contains(t, result.Error, "not a regular file")
|
||||
}
|
||||
|
||||
func TestReadSandboxFileSuppressesBinaryWithoutBase64(t *testing.T) {
|
||||
content := []byte{0xff, 0x00, 0x01}
|
||||
source := &fakeSandboxFileSource{
|
||||
|
|
|
|||
|
|
@ -54,12 +54,11 @@ type dockerEngineAPI interface {
|
|||
ExecAttach(ctx context.Context, execID string, options client.ExecAttachOptions) (client.ExecAttachResult, error)
|
||||
ExecInspect(ctx context.Context, execID string, options client.ExecInspectOptions) (client.ExecInspectResult, error)
|
||||
|
||||
CopyToContainer(
|
||||
ctx context.Context, containerID string, options client.CopyToContainerOptions,
|
||||
) (client.CopyToContainerResult, error)
|
||||
CopyFromContainer(
|
||||
ctx context.Context, containerID string, options client.CopyFromContainerOptions,
|
||||
) (client.CopyFromContainerResult, error)
|
||||
// ContainerStatPath is the one archive endpoint this adapter uses, and only
|
||||
// against the activity marker's fixed path. The copy endpoints are
|
||||
// deliberately absent: they run as root and resolve symlinks, so exposing
|
||||
// them to caller-supplied paths would undo the file operations' reliance on
|
||||
// the kernel for access control (see DockerRemoteClient.WriteFile).
|
||||
ContainerStatPath(
|
||||
ctx context.Context, containerID string, options client.ContainerStatPathOptions,
|
||||
) (client.ContainerStatPathResult, error)
|
||||
|
|
|
|||
|
|
@ -235,6 +235,38 @@ time.sleep(60)
|
|||
t.Fatalf("timeout left %s 'sleep 120' process(es) running: %#v", got, survivors)
|
||||
}
|
||||
})
|
||||
|
||||
// The entrypoint is a plain `sleep`, which never calls wait(). A background
|
||||
// process that outlives the exec which started it is reparented to PID 1,
|
||||
// so without tini in front of it every such process becomes a permanent Z
|
||||
// entry and a long session eventually exhausts PidsLimit. Measured on a
|
||||
// real daemon: three orphans leave three zombies without HostConfig.Init
|
||||
// and none with it.
|
||||
t.Run("OrphanedProcessesAreReaped", func(t *testing.T) {
|
||||
executor := manager.SessionShellExecutor()
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err := executor.ExecShellCommand(
|
||||
ctx, sessionID, "(sleep 0.2 &) ; exit 0",
|
||||
SessionWorkspaceRoot, 30*time.Second, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("spawn orphan %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
const probe = `n=0; for p in /proc/[0-9]*; do ` +
|
||||
`s=$(awk '{print $3}' "$p/stat" 2>/dev/null); ` +
|
||||
`[ "$s" = "Z" ] && n=$((n+1)); done; echo "$n"`
|
||||
zombies, err := executor.ExecShellCommand(
|
||||
ctx, sessionID, probe, SessionWorkspaceRoot, 30*time.Second, nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("zombie probe: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(zombies.Stdout); got != "0" {
|
||||
t.Fatalf("PID 1 left %s zombie(s) unreaped: %#v", got, zombies)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The idle sweeper reclaims a container by the mtime of its activity marker,
|
||||
|
|
|
|||
|
|
@ -32,7 +32,6 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
|
|
@ -58,14 +57,13 @@ const dockerActivityMarker = "/var/lib/weknora-sandbox-activity"
|
|||
// the container is a place to exec into, not a service — and prepares the
|
||||
// activity marker on the way.
|
||||
//
|
||||
// The marker has to be writable by every account that can exec, because
|
||||
// scripts run as the unprivileged sandbox user while shell commands and
|
||||
// filesystem helpers run as root. Creating it here, in the container's own
|
||||
// entrypoint, is the only way to get that without spending an extra API round
|
||||
// trip per sandbox: whoever PID 1 runs as owns the file, and the chmod that
|
||||
// follows lets the other account refresh it. Without this the idle sweeper
|
||||
// would see a session that only ever ran scripts as untouched, and reclaim it
|
||||
// out from under the user.
|
||||
// The marker has to be writable by the sandbox account. PID 1 runs as root so
|
||||
// that it can create the file at all, but every exec that would refresh it —
|
||||
// scripts, shell commands, filesystem helpers — runs as the unprivileged user.
|
||||
// Creating it here, in the container's own entrypoint, avoids an extra API
|
||||
// round trip per sandbox, and the chmod that follows is what lets that account
|
||||
// touch it. Without this the idle sweeper would see a session that only ever
|
||||
// ran scripts as untouched, and reclaim it out from under the user.
|
||||
var dockerSandboxEntrypoint = []string{
|
||||
"/bin/sh", "-c",
|
||||
"touch " + dockerActivityMarker + " 2>/dev/null; " +
|
||||
|
|
@ -323,10 +321,20 @@ func (c *DockerRemoteClient) hostConfig(policy RemoteNetworkPolicy) *container.H
|
|||
SecurityOpt: []string{"no-new-privileges"},
|
||||
Runtime: c.settings.Runtime,
|
||||
NetworkMode: container.NetworkMode(c.networkMode(policy)),
|
||||
// The entrypoint is a plain `sleep`, which never calls wait(). Without
|
||||
// tini in front of it, a background process outliving the exec that
|
||||
// started it becomes an unreaped zombie on exit, and a long session
|
||||
// accumulates them until PidsLimit is exhausted and every further exec
|
||||
// fails.
|
||||
Init: &dockerInitProcess,
|
||||
}
|
||||
return hostConfig
|
||||
}
|
||||
|
||||
// dockerInitProcess is addressable because HostConfig.Init is a *bool: unset
|
||||
// means "follow the daemon default", which is not what this backend wants.
|
||||
var dockerInitProcess = true
|
||||
|
||||
// networkMode resolves the effective Docker network for a sandbox.
|
||||
//
|
||||
// Docker filters at L3/L4 only, so the domain-level allow/deny lists in
|
||||
|
|
@ -679,7 +687,22 @@ func dockerExecWasKilled(exitCode int) bool {
|
|||
return exitCode == 137 || exitCode == 124
|
||||
}
|
||||
|
||||
// WriteFile uploads one file through the archive endpoint.
|
||||
// WriteFile writes one file as the sandbox account.
|
||||
//
|
||||
// This and its Read/Stat counterparts deliberately avoid the Engine's archive
|
||||
// endpoints (CopyToContainer, CopyFromContainer, ContainerStatPath). Those are
|
||||
// served by the daemon, which means two things at once: they ignore the exec
|
||||
// user and act as root, and they resolve symlinks on the way. That combination
|
||||
// is unsafe here, because the sandbox account can write anywhere under
|
||||
// /workspace while every caller-facing path guard in this repository is a
|
||||
// string prefix test. A model that runs `ln -s /root /workspace/output/esc`
|
||||
// leaves /workspace/output/esc/secret.txt passing those guards, and the daemon
|
||||
// then reads it out as root — confirmed against a real daemon, not theorised.
|
||||
//
|
||||
// Running these as DefaultSandboxExecUser hands the decision to the kernel
|
||||
// instead: a path the sandbox account cannot reach on its own stays
|
||||
// unreachable regardless of what a link points at, and there is no window
|
||||
// between checking and using in which the link could be repointed.
|
||||
func (c *DockerRemoteClient) WriteFile(
|
||||
ctx context.Context,
|
||||
handle RemoteSandboxHandle,
|
||||
|
|
@ -698,54 +721,31 @@ func (c *DockerRemoteClient) WriteFile(
|
|||
return err
|
||||
}
|
||||
|
||||
var archive bytes.Buffer
|
||||
writer := tar.NewWriter(&archive)
|
||||
header := &tar.Header{
|
||||
Name: path.Base(clean),
|
||||
Mode: 0o644,
|
||||
Size: int64(len(content)),
|
||||
ModTime: time.Now(),
|
||||
// Files land owned by the sandbox account so scripts can read (and
|
||||
// replace) their own inputs; the archive endpoint applies these ids
|
||||
// verbatim when CopyUIDGID is set.
|
||||
Uid: dockerSandboxUID,
|
||||
Gid: dockerSandboxGID,
|
||||
}
|
||||
if err := writer.WriteHeader(header); err != nil {
|
||||
return dockerError("WriteFile", err)
|
||||
}
|
||||
if _, err := writer.Write(content); err != nil {
|
||||
return dockerError("WriteFile", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return dockerError("WriteFile", err)
|
||||
}
|
||||
|
||||
_, err = c.api.CopyToContainer(ctx, id, client.CopyToContainerOptions{
|
||||
DestinationPath: path.Dir(clean),
|
||||
Content: &archive,
|
||||
CopyUIDGID: true,
|
||||
// The path travels as a positional argument so a name containing shell
|
||||
// metacharacters cannot change what the redirect targets.
|
||||
result, err := c.Exec(ctx, &dockerSandboxHandle{id: id}, RemoteExecRequest{
|
||||
Command: "sh",
|
||||
Args: []string{"-c", `cat > "$1"`, "weknora-write", clean},
|
||||
Stdin: string(content),
|
||||
User: DefaultSandboxExecUser,
|
||||
Timeout: dockerFilesystemOpTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
return dockerError("WriteFile", err)
|
||||
}
|
||||
if result.ExitCode != 0 {
|
||||
return dockerFileOpError("WriteFile", clean, result.Stderr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// dockerSandboxUID / dockerSandboxGID are the ids of DefaultSandboxExecUser.
|
||||
// The template contract fixes them at 1000, the same convention E2B templates
|
||||
// use, so uploaded files can be owned correctly without an extra lookup.
|
||||
const (
|
||||
dockerSandboxUID = 1000
|
||||
dockerSandboxGID = 1000
|
||||
// dockerSandboxPID1User overrides the image USER so the entrypoint can create
|
||||
// the world-writable activity marker. Numeric 0 does not depend on a root
|
||||
// account existing by name in a custom image.
|
||||
const dockerSandboxPID1User = "0"
|
||||
|
||||
// dockerSandboxPID1User overrides the image USER so the entrypoint can
|
||||
// create the world-writable activity marker. Numeric 0 does not depend
|
||||
// on a root account existing by name in a custom image.
|
||||
dockerSandboxPID1User = "0"
|
||||
)
|
||||
|
||||
// ReadFile downloads one file through the archive endpoint.
|
||||
// ReadFile reads one file as the sandbox account. See WriteFile for why this
|
||||
// does not use the archive endpoint.
|
||||
func (c *DockerRemoteClient) ReadFile(
|
||||
ctx context.Context,
|
||||
handle RemoteSandboxHandle,
|
||||
|
|
@ -759,44 +759,26 @@ func (c *DockerRemoteClient) ReadFile(
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response, err := c.api.CopyFromContainer(ctx, id, client.CopyFromContainerOptions{
|
||||
SourcePath: clean,
|
||||
result, err := c.Exec(ctx, &dockerSandboxHandle{id: id}, RemoteExecRequest{
|
||||
Command: "cat",
|
||||
Args: []string{"--", clean},
|
||||
User: DefaultSandboxExecUser,
|
||||
Timeout: dockerFilesystemOpTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, dockerError("ReadFile", err)
|
||||
}
|
||||
defer func() { _ = response.Content.Close() }()
|
||||
|
||||
reader := tar.NewReader(response.Content)
|
||||
for {
|
||||
header, err := reader.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil, &RemoteError{
|
||||
Kind: RemoteErrorKindNotFound,
|
||||
Provider: SandboxTypeDocker,
|
||||
Op: "ReadFile",
|
||||
Message: "archive contained no regular file for " + clean,
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, dockerError("ReadFile", err)
|
||||
}
|
||||
switch header.Typeflag {
|
||||
case tar.TypeDir:
|
||||
return nil, dockerInvalidRequest("ReadFile", clean+" is a directory")
|
||||
case tar.TypeReg:
|
||||
content, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
return nil, dockerError("ReadFile", err)
|
||||
}
|
||||
return content, nil
|
||||
default:
|
||||
continue
|
||||
}
|
||||
if result.ExitCode != 0 {
|
||||
return nil, dockerFileOpError("ReadFile", clean, result.Stderr)
|
||||
}
|
||||
return []byte(result.Stdout), nil
|
||||
}
|
||||
|
||||
// Stat returns metadata for one path.
|
||||
//
|
||||
// find does not follow symlinks, so a link reports as RemoteEntryOther rather
|
||||
// than as whatever it points at. Callers that only accept regular files
|
||||
// therefore refuse it before any read is attempted.
|
||||
func (c *DockerRemoteClient) Stat(
|
||||
ctx context.Context,
|
||||
handle RemoteSandboxHandle,
|
||||
|
|
@ -810,22 +792,57 @@ func (c *DockerRemoteClient) Stat(
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stat, err := c.api.ContainerStatPath(ctx, id, client.ContainerStatPathOptions{Path: clean})
|
||||
result, err := c.Exec(ctx, &dockerSandboxHandle{id: id}, RemoteExecRequest{
|
||||
Command: "find",
|
||||
Args: []string{
|
||||
clean, "-maxdepth", "0",
|
||||
"-printf", `%y\t%s\t%T@\t%p\n`,
|
||||
},
|
||||
User: DefaultSandboxExecUser,
|
||||
Timeout: dockerFilesystemOpTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, dockerError("Stat", err)
|
||||
}
|
||||
entry := &RemoteStatEntry{
|
||||
Path: clean,
|
||||
Type: RemoteEntryFile,
|
||||
Size: stat.Stat.Size,
|
||||
ModTime: stat.Stat.Mtime,
|
||||
if result.ExitCode != 0 {
|
||||
return nil, dockerFileOpError("Stat", clean, result.Stderr)
|
||||
}
|
||||
if stat.Stat.Mode.IsDir() {
|
||||
entry.Type = RemoteEntryDir
|
||||
} else if !stat.Stat.Mode.IsRegular() {
|
||||
entry.Type = RemoteEntryOther
|
||||
entries := parseDockerFindOutput(result.Stdout)
|
||||
if len(entries) == 0 {
|
||||
return nil, &RemoteError{
|
||||
Kind: RemoteErrorKindNotFound,
|
||||
Provider: SandboxTypeDocker,
|
||||
Op: "Stat",
|
||||
Message: clean + " does not exist",
|
||||
}
|
||||
}
|
||||
return &RemoteStatEntry{
|
||||
Path: entries[0].Path,
|
||||
Type: entries[0].Type,
|
||||
Size: entries[0].Size,
|
||||
ModTime: entries[0].ModTime,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// dockerFileOpError classifies a failed filesystem helper. A missing path is
|
||||
// NotFound so callers can treat it as "nothing there"; everything else,
|
||||
// permission denials included, is an invalid request carrying the tool's own
|
||||
// complaint rather than a synthesised one.
|
||||
func dockerFileOpError(op, clean, stderr string) error {
|
||||
if strings.Contains(stderr, "No such file or directory") {
|
||||
return &RemoteError{
|
||||
Kind: RemoteErrorKindNotFound,
|
||||
Provider: SandboxTypeDocker,
|
||||
Op: op,
|
||||
Message: clean + " does not exist",
|
||||
}
|
||||
}
|
||||
return &RemoteError{
|
||||
Kind: RemoteErrorKindInvalidRequest,
|
||||
Provider: SandboxTypeDocker,
|
||||
Op: op,
|
||||
Message: fmt.Sprintf("%s %s: %s", op, clean, firstNonEmptyLine(stderr)),
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// MakeDir creates a directory (and its parents) inside the sandbox.
|
||||
|
|
@ -1061,13 +1078,12 @@ func dockerCleanPath(op, raw string) (string, error) {
|
|||
|
||||
// dockerReservedPathPrefixes are refused for every file operation.
|
||||
//
|
||||
// Unlike the envd-backed backends, the archive endpoints (WriteFile, ReadFile,
|
||||
// Stat) are served by the daemon itself and therefore ignore the exec user
|
||||
// entirely: they read and write as root no matter what a caller asks for. The
|
||||
// callers in this repository only ever address /workspace, so this is defence
|
||||
// in depth rather than a live hole — but it is what keeps a future caller from
|
||||
// turning a file read into a way to lift PID 1's environment out of /proc, or
|
||||
// a file write into a way to backdate the sweeper's own bookkeeping.
|
||||
// File operations run as the sandbox account (see WriteFile), so the kernel
|
||||
// already decides what is reachable and this list is not what keeps /etc or
|
||||
// another session's data safe. It exists for the paths the sandbox account
|
||||
// legitimately can touch but never should through this API: /proc and /sys
|
||||
// expose the container's own runtime state, and the activity marker is the
|
||||
// sweeper's bookkeeping, which a session must not be able to backdate.
|
||||
var dockerReservedPathPrefixes = []string{
|
||||
"/proc",
|
||||
"/sys",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
|
|
@ -10,7 +9,6 @@ import (
|
|||
"io"
|
||||
"iter"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
|
@ -63,9 +61,6 @@ type fakeDockerEngine struct {
|
|||
// sweeper's re-check before deletion is exercised.
|
||||
statHook func(path string) (container.PathStat, bool)
|
||||
statErr error
|
||||
copiedTo []client.CopyToContainerOptions
|
||||
copyFrom []byte
|
||||
copyErr error
|
||||
|
||||
images []image.Summary
|
||||
imagePresent map[string]bool
|
||||
|
|
@ -206,30 +201,6 @@ func (f *fakeDockerEngine) ExecInspect(
|
|||
return client.ExecInspectResult{ExitCode: f.execExit}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDockerEngine) CopyToContainer(
|
||||
_ context.Context, _ string, options client.CopyToContainerOptions,
|
||||
) (client.CopyToContainerResult, error) {
|
||||
if f.copyErr != nil {
|
||||
return client.CopyToContainerResult{}, f.copyErr
|
||||
}
|
||||
content, _ := io.ReadAll(options.Content)
|
||||
options.Content = bytes.NewReader(content)
|
||||
f.copiedTo = append(f.copiedTo, options)
|
||||
f.copyFrom = content
|
||||
return client.CopyToContainerResult{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDockerEngine) CopyFromContainer(
|
||||
_ context.Context, _ string, _ client.CopyFromContainerOptions,
|
||||
) (client.CopyFromContainerResult, error) {
|
||||
if f.copyErr != nil {
|
||||
return client.CopyFromContainerResult{}, f.copyErr
|
||||
}
|
||||
return client.CopyFromContainerResult{
|
||||
Content: io.NopCloser(bytes.NewReader(f.copyFrom)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDockerEngine) ContainerStatPath(
|
||||
_ context.Context, _ string, options client.ContainerStatPathOptions,
|
||||
) (client.ContainerStatPathResult, error) {
|
||||
|
|
@ -384,6 +355,9 @@ func TestDockerClientCreateAppliesIsolationAndMetadata(t *testing.T) {
|
|||
require.Equal(t, int64(DefaultDockerCPULimit*1e9), host.NanoCPUs)
|
||||
require.Equal(t, DefaultDockerPidsLimit, *host.PidsLimit)
|
||||
require.Equal(t, container.NetworkMode("bridge"), host.NetworkMode)
|
||||
require.NotNil(t, host.Init)
|
||||
require.True(t, *host.Init,
|
||||
"`sleep` never reaps, so without tini a long session fills PidsLimit with zombies")
|
||||
require.Equal(t, []string{"container-1"}, engine.started)
|
||||
}
|
||||
|
||||
|
|
@ -637,7 +611,8 @@ func TestDockerClientExecShellPassesCommandAsPositionalArgument(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
opts := engine.execOptions[0]
|
||||
require.Equal(t, []string{"weknora-exec", `echo "a b"; rm -rf /nope`}, opts.Cmd[3:])
|
||||
require.Equal(t, "root", opts.User, "an unspecified user means root, matching envd backends")
|
||||
require.Equal(t, "root", opts.User,
|
||||
"a blank user is the manager's bootstrap escape hatch; callers name the account")
|
||||
}
|
||||
|
||||
func TestDockerClientExecRejectsShellWithArgs(t *testing.T) {
|
||||
|
|
@ -677,7 +652,11 @@ func TestDockerClientExecWritesStdin(t *testing.T) {
|
|||
require.True(t, engine.execOptions[0].AttachStdin)
|
||||
}
|
||||
|
||||
func TestDockerClientWriteFileUploadsArchiveOwnedBySandboxUser(t *testing.T) {
|
||||
// The archive endpoint would apply this write as root and resolve symlinks on
|
||||
// the way, so a link planted under the writable workspace could redirect an
|
||||
// upload onto a file the sandbox account cannot touch. Writing through exec
|
||||
// puts the kernel back in charge.
|
||||
func TestDockerClientWriteFileRunsAsSandboxUserOverExec(t *testing.T) {
|
||||
engine := newFakeDockerEngine()
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
||||
|
|
@ -685,39 +664,120 @@ func TestDockerClientWriteFileUploadsArchiveOwnedBySandboxUser(t *testing.T) {
|
|||
"/workspace/input/note.txt", []byte("hello"))
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, engine.copiedTo, 1)
|
||||
require.Equal(t, "/workspace/input", engine.copiedTo[0].DestinationPath)
|
||||
require.True(t, engine.copiedTo[0].CopyUIDGID)
|
||||
require.Contains(t, engine.execOptions[0].Cmd, "mkdir",
|
||||
"the parent directory has no archive-API equivalent and must be exec'd")
|
||||
require.Equal(t, DefaultSandboxExecUser, engine.execOptions[0].User,
|
||||
require.Len(t, engine.execOptions, 2, "one mkdir for the parent, one write")
|
||||
mkdir, write := engine.execOptions[0], engine.execOptions[1]
|
||||
|
||||
require.Contains(t, mkdir.Cmd, "mkdir")
|
||||
require.Equal(t, DefaultSandboxExecUser, mkdir.User,
|
||||
"mkdir as root would leave nested dirs unwritable by skill scripts")
|
||||
|
||||
content, err := docker.ReadFile(context.Background(), testHandle("c"),
|
||||
"/workspace/input/note.txt")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("hello"), content)
|
||||
require.Equal(t, DefaultSandboxExecUser, write.User)
|
||||
require.True(t, write.AttachStdin)
|
||||
require.Equal(t, "hello", engine.execStdin.String())
|
||||
require.Equal(t,
|
||||
[]string{"weknora-exec", "sh", "-c", `cat > "$1"`, "weknora-write", "/workspace/input/note.txt"},
|
||||
write.Cmd[3:],
|
||||
"the destination must reach the shell as a positional arg, never interpolated")
|
||||
}
|
||||
|
||||
func TestDockerClientReadFileRejectsDirectoryArchive(t *testing.T) {
|
||||
func TestDockerClientReadFileRunsAsSandboxUserOverExec(t *testing.T) {
|
||||
engine := newFakeDockerEngine()
|
||||
var archive bytes.Buffer
|
||||
writer := tar.NewWriter(&archive)
|
||||
require.NoError(t, writer.WriteHeader(&tar.Header{
|
||||
Name: "output", Typeflag: tar.TypeDir, Mode: 0o755,
|
||||
}))
|
||||
require.NoError(t, writer.WriteHeader(&tar.Header{
|
||||
Name: "output/nested.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3,
|
||||
}))
|
||||
_, err := writer.Write([]byte("hi\n"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
engine.copyFrom = archive.Bytes()
|
||||
engine.execStdout = "report body\n"
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
||||
_, err = newTestDockerClient(t, engine).ReadFile(
|
||||
context.Background(), testHandle("c"), "/workspace/output")
|
||||
require.True(t, IsRemoteInvalidRequest(err),
|
||||
"a directory archive must not return the first nested file")
|
||||
content, err := docker.ReadFile(context.Background(), testHandle("c"),
|
||||
"/workspace/output/report.txt")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("report body\n"), content)
|
||||
|
||||
require.Len(t, engine.execOptions, 1)
|
||||
require.Equal(t, DefaultSandboxExecUser, engine.execOptions[0].User)
|
||||
require.Equal(t,
|
||||
[]string{"weknora-exec", "cat", "--", "/workspace/output/report.txt"},
|
||||
engine.execOptions[0].Cmd[3:])
|
||||
}
|
||||
|
||||
// A path the sandbox account cannot read must surface as a refusal rather than
|
||||
// as content, and must stay distinguishable from a path that simply is not
|
||||
// there: callers treat NotFound as "nothing produced yet".
|
||||
func TestDockerClientReadFileMapsFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
stderr string
|
||||
refused func(error) bool
|
||||
}{
|
||||
{
|
||||
name: "missing path",
|
||||
stderr: "cat: /workspace/output/gone.txt: No such file or directory",
|
||||
refused: IsRemoteNotFound,
|
||||
},
|
||||
{
|
||||
name: "unreadable through a planted symlink",
|
||||
stderr: "cat: /workspace/output/esc/secret.txt: Permission denied",
|
||||
refused: IsRemoteInvalidRequest,
|
||||
},
|
||||
{
|
||||
name: "directory",
|
||||
stderr: "cat: /workspace/output: Is a directory",
|
||||
refused: IsRemoteInvalidRequest,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
engine := newFakeDockerEngine()
|
||||
engine.execExit = 1
|
||||
engine.execStderr = tt.stderr
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
||||
_, err := docker.ReadFile(context.Background(), testHandle("c"),
|
||||
"/workspace/output/probe")
|
||||
require.True(t, tt.refused(err), "got %v", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The attack this closes: the sandbox account can write to /workspace, and
|
||||
// every caller-facing guard is a string prefix test, so `ln -s /root
|
||||
// /workspace/output/esc` used to leave the daemon reading /root as root.
|
||||
// find does not follow links, so the link reports as itself and callers that
|
||||
// require a regular file refuse it before any read is attempted.
|
||||
func TestDockerClientStatReportsSymlinkAsOther(t *testing.T) {
|
||||
engine := newFakeDockerEngine()
|
||||
engine.execStdout = "l\t4\t1786565482.0000000000\t/workspace/output/esc\n"
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
||||
entry, err := docker.Stat(context.Background(), testHandle("c"),
|
||||
"/workspace/output/esc")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, RemoteEntryOther, entry.Type,
|
||||
"a symlink must not be reported as the file it points at")
|
||||
}
|
||||
|
||||
// Guards the property the symlink fix rests on. The archive endpoints ignored
|
||||
// the requested user and ran as root; if any file operation goes back to one,
|
||||
// this catches it without needing a daemon to prove the consequence.
|
||||
func TestDockerClientFileOperationsNeverRunAsRoot(t *testing.T) {
|
||||
engine := newFakeDockerEngine()
|
||||
engine.execStdout = "f\t3\t1786565482.0000000000\t/workspace/output/a.txt\n"
|
||||
docker := newTestDockerClient(t, engine)
|
||||
ctx := context.Background()
|
||||
handle := testHandle("c")
|
||||
|
||||
require.NoError(t, docker.WriteFile(ctx, handle, "/workspace/output/a.txt", []byte("x")))
|
||||
_, err := docker.ReadFile(ctx, handle, "/workspace/output/a.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = docker.Stat(ctx, handle, "/workspace/output/a.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = docker.ListDir(ctx, handle, "/workspace/output")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, docker.MakeDir(ctx, handle, "/workspace/output/sub"))
|
||||
require.NoError(t, docker.Remove(ctx, handle, "/workspace/output/a.txt"))
|
||||
|
||||
require.NotEmpty(t, engine.execOptions)
|
||||
for i, opts := range engine.execOptions {
|
||||
require.Equal(t, DefaultSandboxExecUser, opts.User,
|
||||
"exec %d (%v) must not run as root", i, opts.Cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerClientPathsMustBeAbsolute(t *testing.T) {
|
||||
|
|
@ -763,16 +823,22 @@ func TestDockerClientListDirMissingDirectoryIsNotFound(t *testing.T) {
|
|||
|
||||
func TestDockerClientStatMapsEntryType(t *testing.T) {
|
||||
engine := newFakeDockerEngine()
|
||||
engine.statResult["/workspace/output"] = container.PathStat{
|
||||
Size: 4096, Mode: os.ModeDir | 0o755, Mtime: time.Now(),
|
||||
}
|
||||
engine.execStdout = "d\t4096\t1786565482.0000000000\t/workspace/output\n"
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
||||
entry, err := docker.Stat(context.Background(), testHandle("c"), "/workspace/output")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, RemoteEntryDir, entry.Type)
|
||||
require.Equal(t, int64(4096), entry.Size)
|
||||
require.Equal(t,
|
||||
[]string{"weknora-exec", "find", "/workspace/output", "-maxdepth", "0", "-printf", `%y\t%s\t%T@\t%p\n`},
|
||||
engine.execOptions[0].Cmd[3:])
|
||||
|
||||
_, err = docker.Stat(context.Background(), testHandle("c"), "/workspace/missing")
|
||||
missing := newFakeDockerEngine()
|
||||
missing.execExit = 1
|
||||
missing.execStderr = "find: '/workspace/missing': No such file or directory"
|
||||
_, err = newTestDockerClient(t, missing).Stat(
|
||||
context.Background(), testHandle("c"), "/workspace/missing")
|
||||
require.True(t, IsRemoteNotFound(err))
|
||||
}
|
||||
|
||||
|
|
@ -823,9 +889,10 @@ func TestValidateDockerRemoteTLS(t *testing.T) {
|
|||
require.NoError(t, ValidateDockerRemoteTLS("tcp://10.0.0.5:2376", "/etc/weknora/docker-certs"))
|
||||
}
|
||||
|
||||
// The archive endpoints are served by the daemon and ignore the exec user, so
|
||||
// they read and write as root. Pseudo-filesystems and the sweeper's own marker
|
||||
// must not be addressable through them.
|
||||
// File operations run as the sandbox account, so the kernel decides what is
|
||||
// reachable. This list covers what that account legitimately can touch but
|
||||
// never should through this API: the container's own runtime state, and the
|
||||
// sweeper's marker, which a session must not be able to backdate.
|
||||
func TestDockerCleanPathRefusesReservedPaths(t *testing.T) {
|
||||
engine := newFakeDockerEngine()
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
|
@ -848,7 +915,7 @@ func TestDockerCleanPathRefusesReservedPaths(t *testing.T) {
|
|||
require.Error(t, err, target)
|
||||
}
|
||||
|
||||
require.Empty(t, engine.copiedTo, "a refused path must never reach the daemon")
|
||||
require.Empty(t, engine.execOptions, "a refused path must never reach the daemon")
|
||||
}
|
||||
|
||||
func TestDockerHostNeedsDialGuard(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -105,18 +105,6 @@ func (a *dockerRPCTimeoutAPI) ExecInspect(
|
|||
return a.inner.ExecInspect(rpcCtx, execID, options)
|
||||
}
|
||||
|
||||
func (a *dockerRPCTimeoutAPI) CopyToContainer(
|
||||
ctx context.Context, containerID string, options client.CopyToContainerOptions,
|
||||
) (client.CopyToContainerResult, error) {
|
||||
return a.inner.CopyToContainer(ctx, containerID, options)
|
||||
}
|
||||
|
||||
func (a *dockerRPCTimeoutAPI) CopyFromContainer(
|
||||
ctx context.Context, containerID string, options client.CopyFromContainerOptions,
|
||||
) (client.CopyFromContainerResult, error) {
|
||||
return a.inner.CopyFromContainer(ctx, containerID, options)
|
||||
}
|
||||
|
||||
func (a *dockerRPCTimeoutAPI) ContainerStatPath(
|
||||
ctx context.Context, containerID string, options client.ContainerStatPathOptions,
|
||||
) (client.ContainerStatPathResult, error) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue