| 1 | package containerenv |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | ) |
| 14 | |
| 15 | type State struct { |
| 16 | Exists bool `json:"exists"` |
| 17 | Running bool `json:"running"` |
| 18 | Ready bool `json:"ready"` |
| 19 | ContainerID string `json:"container_id,omitempty"` |
| 20 | PID int `json:"pid,omitempty"` |
| 21 | MemoryBytes int64 `json:"memory_bytes"` |
| 22 | CPUs int `json:"cpus"` |
| 23 | BrowserAddress string `json:"browser_address,omitempty"` |
| 24 | VNCAddress string `json:"vnc_address,omitempty"` |
| 25 | StoragePath string `json:"storage_path,omitempty"` |
| 26 | ResourcesVerified bool `json:"resources_verified"` |
| 27 | ResourceError string `json:"resource_error,omitempty"` |
| 28 | PIDs int64 `json:"pids"` |
| 29 | MountsReady bool `json:"mounts_ready"` |
| 30 | MountError string `json:"mount_error,omitempty"` |
| 31 | } |
| 32 | |
| 33 | type Inspection struct { |
| 34 | State State `json:"state"` |
| 35 | Rootless bool `json:"rootless"` |
| 36 | NetworkConfined bool `json:"network_confined"` |
| 37 | FilesystemConfined bool `json:"filesystem_confined"` |
| 38 | Evidence string `json:"evidence"` |
| 39 | MountPropagation MountPropagation `json:"mount_propagation"` |
| 40 | } |
| 41 | |
| 42 | type engineContainer struct { |
| 43 | ID string `json:"Id"` |
| 44 | Image string `json:"Image"` |
| 45 | State struct { |
| 46 | Running bool |
| 47 | Pid int |
| 48 | } |
| 49 | Config struct { |
| 50 | Labels map[string]string |
| 51 | Image string |
| 52 | } |
| 53 | HostConfig struct { |
| 54 | Privileged bool |
| 55 | NetworkMode string |
| 56 | PidMode string |
| 57 | IpcMode string |
| 58 | CgroupnsMode string |
| 59 | CgroupParent string |
| 60 | UsernsMode string |
| 61 | Binds []string |
| 62 | ExtraHosts []string |
| 63 | CapAdd []string |
| 64 | Memory int64 |
| 65 | NanoCpus int64 |
| 66 | Devices []struct { |
| 67 | PathOnHost string |
| 68 | PathInContainer string |
| 69 | } |
| 70 | } |
| 71 | Mounts []struct { |
| 72 | Type string |
| 73 | Source string |
| 74 | Destination string |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func (r *Runtime) command(ctx context.Context, args ...string) *exec.Cmd { |
| 79 | if r.config.Engine == "docker" { |
| 80 | |
| 81 | |
| 82 | args = append([]string{"--config", filepath.Join(r.InstanceDir(), "client-config"), "--host", r.config.Socket}, args...) |
| 83 | } |
| 84 | command := exec.CommandContext(ctx, r.config.Executable, args...) |
| 85 | for _, entry := range os.Environ() { |
| 86 | name, _, _ := strings.Cut(entry, "=") |
| 87 | switch name { |
| 88 | case "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "CONTAINER_HOST", "CONTAINER_CONNECTION": |
| 89 | continue |
| 90 | } |
| 91 | command.Env = append(command.Env, entry) |
| 92 | } |
| 93 | return command |
| 94 | } |
| 95 | |
| 96 | func (r *Runtime) output(ctx context.Context, args ...string) ([]byte, error) { |
| 97 | command := r.command(ctx, args...) |
| 98 | var output, diagnostic bytes.Buffer |
| 99 | command.Stdout = &limitedWriter{writer: &output, left: 1 << 20} |
| 100 | command.Stderr = &limitedWriter{writer: &diagnostic, left: 4096} |
| 101 | if err := command.Run(); err != nil { |
| 102 | return nil, fmt.Errorf("容器引擎操作失败: %w: %s", err, strings.TrimSpace(diagnostic.String())) |
| 103 | } |
| 104 | return output.Bytes(), nil |
| 105 | } |
| 106 | |
| 107 | type limitedWriter struct { |
| 108 | writer *bytes.Buffer |
| 109 | left int |
| 110 | } |
| 111 | |
| 112 | func (w *limitedWriter) Write(data []byte) (int, error) { |
| 113 | if len(data) > w.left { |
| 114 | return 0, errors.New("container engine output limit exceeded") |
| 115 | } |
| 116 | n, err := w.writer.Write(data) |
| 117 | w.left -= n |
| 118 | return n, err |
| 119 | } |
| 120 | |
| 121 | func (r *Runtime) inspectContainer(ctx context.Context) (*engineContainer, error) { |
| 122 | |
| 123 | |
| 124 | data, err := r.output(ctx, "container", "ls", "--all", "--filter", "label="+profileLabel+"="+r.identity, "--format", "{{.ID}}") |
| 125 | if err != nil { |
| 126 | return nil, err |
| 127 | } |
| 128 | id := strings.TrimSpace(string(data)) |
| 129 | if id == "" { |
| 130 | return nil, nil |
| 131 | } |
| 132 | if strings.ContainsAny(id, " \r\n\t") { |
| 133 | return nil, errors.New("容器标识不唯一") |
| 134 | } |
| 135 | data, err = r.output(ctx, "container", "inspect", id) |
| 136 | if err != nil { |
| 137 | return nil, err |
| 138 | } |
| 139 | var found []engineContainer |
| 140 | if json.Unmarshal(data, &found) != nil || len(found) != 1 || found[0].Config.Labels[profileLabel] != r.identity { |
| 141 | return nil, errors.New("容器身份与当前 Cage 配置不匹配") |
| 142 | } |
| 143 | return &found[0], nil |
| 144 | } |
| 145 | |
| 146 | func (r *Runtime) State(ctx context.Context) (State, error) { |
| 147 | container, err := r.inspectContainer(ctx) |
| 148 | if err != nil { |
| 149 | return State{}, err |
| 150 | } |
| 151 | if container == nil { |
| 152 | storage, err := r.StoragePath(ctx) |
| 153 | return State{CPUs: r.config.CPUs, MemoryBytes: r.config.MemoryBytes, StoragePath: storage}, err |
| 154 | } |
| 155 | state := State{Exists: true, Running: container.State.Running, ContainerID: container.ID, PID: container.State.Pid, MemoryBytes: container.HostConfig.Memory, CPUs: int(container.HostConfig.NanoCpus / 1e9)} |
| 156 | state.StoragePath, err = r.StoragePath(ctx) |
| 157 | if err != nil { |
| 158 | return State{}, err |
| 159 | } |
| 160 | if state.Running { |
| 161 | mounts, mountErr := r.inspectMounts(container) |
| 162 | if mountErr != nil { |
| 163 | state.MountError = mountErr.Error() |
| 164 | } else { |
| 165 | state.MountsReady = mounts.Ready() |
| 166 | } |
| 167 | resources, resourceErr := r.verifyResources(ctx, container.ID) |
| 168 | if resourceErr != nil { |
| 169 | state.MemoryBytes = 0 |
| 170 | state.CPUs = 0 |
| 171 | state.ResourceError = resourceErr.Error() |
| 172 | } else { |
| 173 | state.MemoryBytes = resources.MemoryBytes |
| 174 | state.CPUs = resources.CPUs |
| 175 | state.PIDs = resources.PIDs |
| 176 | state.ResourcesVerified = true |
| 177 | } |
| 178 | if record, err := r.networkState(ctx, container.ID); err == nil { |
| 179 | state.Ready = state.ResourcesVerified && state.MountsReady |
| 180 | state.BrowserAddress = record.BrowserAddress |
| 181 | state.VNCAddress = record.VNCAddress |
| 182 | } |
| 183 | } |
| 184 | return state, nil |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | func (r *Runtime) StoragePath(ctx context.Context) (string, error) { |
| 191 | format := "{{.DockerRootDir}}" |
| 192 | if r.config.Engine == "podman" { |
| 193 | format = "{{.Store.GraphRoot}}" |
| 194 | } |
| 195 | data, err := r.output(ctx, "info", "--format", format) |
| 196 | if err != nil { |
| 197 | return "", err |
| 198 | } |
| 199 | path := strings.TrimSpace(string(data)) |
| 200 | if !filepath.IsAbs(path) || strings.ContainsAny(path, "\x00\r\n") { |
| 201 | return "", errors.New("容器持久存储位置无效") |
| 202 | } |
| 203 | return path, nil |
| 204 | } |
| 205 | |
| 206 | func (r *Runtime) rootlessEngine(ctx context.Context) (bool, error) { |
| 207 | rootless, limited, err := r.engineSecurity(ctx) |
| 208 | if err != nil { |
| 209 | return false, err |
| 210 | } |
| 211 | if !limited { |
| 212 | return false, errors.New("容器引擎必须使用 systemd 和 cgroup v2,以执行 CPU、内存与进程数限额") |
| 213 | } |
| 214 | return rootless, nil |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | func (r *Runtime) engineSecurity(ctx context.Context) (rootless, limited bool, err error) { |
| 220 | if r.config.Engine == "docker" { |
| 221 | data, err := r.output(ctx, "info", "--format", "{{json .SecurityOptions}}\n{{.CgroupDriver}}\n{{.CgroupVersion}}") |
| 222 | if err != nil { |
| 223 | return false, false, err |
| 224 | } |
| 225 | var options []string |
| 226 | lines := strings.Split(strings.TrimSpace(string(data)), "\n") |
| 227 | if len(lines) != 3 || json.Unmarshal([]byte(lines[0]), &options) != nil { |
| 228 | return false, false, errors.New("无法确认 Docker 安全配置") |
| 229 | } |
| 230 | limited = lines[1] == "systemd" && lines[2] == "2" |
| 231 | for _, option := range options { |
| 232 | if option == "name=rootless" || strings.HasPrefix(option, "name=rootless,") { |
| 233 | return true, limited, nil |
| 234 | } |
| 235 | } |
| 236 | return false, limited, nil |
| 237 | } |
| 238 | data, err := r.output(ctx, "info", "--format", "{{.Host.Security.Rootless}}\n{{.Host.CgroupManager}}\n{{.Host.CgroupVersion}}") |
| 239 | if err != nil { |
| 240 | return false, false, err |
| 241 | } |
| 242 | lines := strings.Split(strings.TrimSpace(string(data)), "\n") |
| 243 | if len(lines) != 3 { |
| 244 | return false, false, errors.New("无法确认 Podman 安全配置") |
| 245 | } |
| 246 | return lines[0] == "true", lines[1] == "systemd" && (lines[2] == "v2" || lines[2] == "2"), nil |
| 247 | } |
| 248 | |
| 249 | func checkContainerConfiguration(container *engineContainer) error { |
| 250 | config := container.HostConfig |
| 251 | if config.Privileged || config.NetworkMode != "none" || (config.PidMode != "" && config.PidMode != "private") || config.IpcMode != "private" || config.CgroupnsMode != "private" { |
| 252 | return errors.New("容器必须使用独立命名空间和禁用默认网络,不能启用特权模式") |
| 253 | } |
| 254 | if len(config.Binds) > 0 { |
| 255 | return errors.New("容器不能直接挂载宿主目录") |
| 256 | } |
| 257 | for _, entry := range config.ExtraHosts { |
| 258 | if entry != "cage:127.0.1.1" { |
| 259 | return errors.New("容器只允许 Cage 主机名的固定回环地址") |
| 260 | } |
| 261 | } |
| 262 | for _, mount := range container.Mounts { |
| 263 | if mount.Type == "bind" || mount.Type == "volume" { |
| 264 | return errors.New("容器存在未经 Cage 文件共享授权的挂载") |
| 265 | } |
| 266 | } |
| 267 | for _, device := range config.Devices { |
| 268 | if (device.PathOnHost != "/dev/fuse" && device.PathOnHost != "/dev/net/tun") || device.PathOnHost != device.PathInContainer { |
| 269 | return errors.New("容器存在额外宿主设备") |
| 270 | } |
| 271 | } |
| 272 | for _, capability := range config.CapAdd { |
| 273 | capability = strings.TrimPrefix(capability, "CAP_") |
| 274 | if capability != "NET_ADMIN" && capability != "SYS_ADMIN" { |
| 275 | return errors.New("容器存在额外系统权限") |
| 276 | } |
| 277 | } |
| 278 | return nil |
| 279 | } |
| 280 | |
| 281 | func (r *Runtime) Inspect(ctx context.Context) (Inspection, error) { |
| 282 | rootless, err := r.rootlessEngine(ctx) |
| 283 | if err != nil { |
| 284 | return Inspection{}, err |
| 285 | } |
| 286 | if !rootless { |
| 287 | return Inspection{}, errors.New("Cage 容器必须由独立 rootless 引擎运行") |
| 288 | } |
| 289 | container, err := r.inspectContainer(ctx) |
| 290 | if err != nil { |
| 291 | return Inspection{}, err |
| 292 | } |
| 293 | if container == nil { |
| 294 | return Inspection{Rootless: true}, nil |
| 295 | } |
| 296 | if err := checkContainerConfiguration(container); err != nil { |
| 297 | return Inspection{}, err |
| 298 | } |
| 299 | if container.HostConfig.CgroupParent != r.resourceSlice() { |
| 300 | return Inspection{}, errors.New("已有容器缺少当前配置的宿主资源边界;保留原数据,拒绝无约束启动") |
| 301 | } |
| 302 | state := State{Exists: true, Running: container.State.Running, ContainerID: container.ID, PID: container.State.Pid, MemoryBytes: container.HostConfig.Memory, CPUs: int(container.HostConfig.NanoCpus / 1e9)} |
| 303 | state.StoragePath, err = r.StoragePath(ctx) |
| 304 | if err != nil { |
| 305 | return Inspection{}, err |
| 306 | } |
| 307 | result := Inspection{State: state, Rootless: true, Evidence: "rootless 引擎;无默认网络或宿主目录挂载;等待运行中的网络与文件共享检查"} |
| 308 | if state.Running { |
| 309 | mounts, err := r.inspectMounts(container) |
| 310 | if err != nil { |
| 311 | return Inspection{}, err |
| 312 | } |
| 313 | result.MountPropagation = mounts |
| 314 | result.State.MountsReady = mounts.Ready() |
| 315 | resources, err := r.verifyResources(ctx, container.ID) |
| 316 | if err != nil { |
| 317 | return Inspection{}, err |
| 318 | } |
| 319 | result.State.MemoryBytes = resources.MemoryBytes |
| 320 | result.State.CPUs = resources.CPUs |
| 321 | result.State.PIDs = resources.PIDs |
| 322 | result.State.ResourcesVerified = true |
| 323 | if record, err := r.networkState(ctx, container.ID); err == nil { |
| 324 | result.State.Ready = mounts.Ready() |
| 325 | result.State.BrowserAddress = record.BrowserAddress |
| 326 | result.State.VNCAddress = record.VNCAddress |
| 327 | result.NetworkConfined = true |
| 328 | result.FilesystemConfined = mounts.Ready() |
| 329 | result.Evidence = "实际 rootless 容器无默认网络或宿主目录挂载;当前外置网络门槛身份已验证,唯一 TAP 通道由宿主接收;默认项目经受限 SFTP 共享并完成双端读写验证" |
| 330 | } |
| 331 | } |
| 332 | return result, nil |
| 333 | } |