Compare commits

..
Author SHA1 Message Date
BaaRai aeb094d5ef server: anchor ask_operator image reads at the task root 2026-12-03 21:49:41 +01:00
BaaRai eb05248804 Merge pull request #939 from BaaRai/fix/archive-symlink
fix(server): keep task archive packing inside the payload
2026-12-03 21:49:28 +01:00
BaaRai 130fe9a0c4 server: keep task archive packing inside the payload
writeTaskArchivePackage listed each directory of the staged run tree and
then opened its files by full path as root. Code running as the executor
uid with a working directory inside the moved run tree could swap a
listed directory for a symlink, so later children were read through it
and root-only files outside the payload were copied into the archive,
then handed back to the executor group on restore.

Walk and open the payload through an os.Root anchored at it, so no
lookup can leave the payload, and refuse the archive when an opened file
is not the regular file the walk listed. Add regression tests that swap
a directory or a file for an outside, a ../ or an inside symlink right
before the packer opens it, plus guards for existing symlinks and for
link and nested ../ entries on extraction.
2026-12-03 21:24:40 +01:00
BaaRai e4f6de91d2 Merge pull request #938 from BaaRai/fix/session-background-tools
fix(agent): disable Norma background-task tools in sandboxed sessions
2026-12-03 21:23:51 +01:00
5 changed files with 593 additions and 62 deletions
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **`ask_operator` reads run-directory images through a task-rooted handle.** The copy path resolved the asking run directory with `EvalSymlinks` and then opened the resolved path, so a worker that replaced its run directory with a symlink to `/` made the confinement root `/`: an absolute `image_path` to a symlink named `*.png` could have the panel copy `/proc/1/environ` or `/app/keys/jwt.key` into `tasks/<id>/uploads`, where the worker reads it. The read and the upload write are now both anchored with `os.Root` at `tasks/<id>`; the run directory must be a real directory, no path component may be a symlink, the opened file must be the one `Lstat` saw, and the copy is bounded to 10 MB. Existing `..`, outside-path and non-image refusals are unchanged.
- **Task archives no longer follow a directory swapped for a symlink while the task is packed.** The packer, running as root, listed each directory of the staged run tree and then opened its files by full path, so code running as the executor uid that kept a working directory inside the run tree could replace a listed directory with a symlink (for example to `/app/keys`) and have root-only files such as the session signing key copied into the archive, then read them back from the run directory after a restore. The packer now walks and opens the payload through an `os.Root` anchored at it, so no lookup can leave the payload, and refuses the archive when a file it opens is not the regular file the walk listed (device and inode compared). Symlinks already present in the run tree are still skipped and never followed. Behaviour change: an archive whose run tree changes this way while it is packed fails instead of completing, and the task stays in place.
- **Agent sessions no longer offer Norma's background-task tools.** Norma adds `Monitor`, `TaskOutput`, `TaskStop` and `TaskList` to every session that does not opt out, and only the connection test and the goal decomposer opted out. `Monitor` starts a shell command in the panel process, not through the sandbox that `Bash` uses, so in `ARTEX_SANDBOX=required` mode a worker, planner, chat or main-agent model could run commands in the panel container, outside the task's worker, and read or write other tasks' workspaces and transcripts. Every agent session is now built through one constructor. It turns these tools off while the sandbox is required, and always for a session that has neither `Bash` nor the interactive shell, so an orchestration agent cannot gain a shell through `Monitor`. Sessions that do have `Bash` or `shell_*` keep them when the sandbox is off: their background runs, PTY sessions and the pause kill switch depend on the same task manager. The constructor also turns a nil tool list into an empty one, because Norma reads nil as "use my own default tools" and installs its unconfined `Bash` and file tools; the tool catalogue resolver also returns an empty list instead of nil when the tools table cannot be read, the case of the Auto chat agent, whose base list is empty.
- **The target gate honors operator-approved egress grants.** The gate compared every target with pins only, while the sandbox proxy allowed every port of an operator-approved CIDR grant: a host already inside a granted task or company scope still raised per-port and bare-host approval prompts (pins match `host:port`, and a request naming the host without a port is covered only by a port-0 pin). `CheckTargets` now also consults the grants the operator approved for the task (its approved, unexpanded `task_scope` rows and the entries frozen into `task_scope_egress` by approved company grants, normalized as the proxy allowlist is): a domain matching a granted domain, an address inside a granted CIDR, or a range fully inside one passes as covered by `scope_grant`, recorded once per process and target key as a system-decided allowed row with the target outcome `scope_grant`. Pins, stored exemptions, block rules and human approvals are unchanged: anything outside a grant is decided as before, and task allow rules play no role, as everywhere in the gate. Related to #830, the mirror gap on the network side.
- **Chat-spawned tasks inherit fully operator-approved companies (#830).** Migration `0025_company_scope_approved.sql` made company scope an explicit operator decision, but `spawn_task` still stamped the whole company link `approved_by_operator=false`, so a chat-spawned task started with an empty egress allowlist and every connection was denied until an operator approved scope again per task (the trap #833 warns about). `CreateTaskWithOptions` now checks each LLM-selected company: one whose scope inventory exists and is entirely operator-approved and to which the calling task itself holds an operator-approved link carries standing consent, so its task link is inserted approved (a spawn with no task caller - chat session or direct API - inherits nothing, per review on #841) and its grant frozen into `task_scope_egress`, exactly as an operator selection does; a company holding any agent-written (unapproved) row, and one with no scope rows, stay coverage-only, so `add_company_scope`, the ScopeSentry sync and invented ids still grant nothing without a fresh operator decision. Provenance is preserved: `source` stays `agent` and the approval column records the inherited consent row by row. Related: #830, #833.
+112 -49
View File
@@ -170,10 +170,11 @@ func askOperatorActivity(text string, att []chatAttachment, derived []string) db
return a
}
// resolveAskOperatorImage maps image_path onto a regular file inside runDir, the
// run directory of the agent that asks (its CWD). Relative paths are resolved from it.
// ".." segments, paths that EvalSymlinks outside runDir, and non-images are refused.
func resolveAskOperatorImage(runDir, src string) (string, error) {
// askOperatorImageRel maps image_path onto a path relative to the task root.
// Relative paths resolve from runName, the run directory of the agent that asks
// (i<intentID>, or main). An absolute path must be inside that run directory.
// ".." segments, paths outside the run directory and non-images are refused.
func askOperatorImageRel(taskDir, runName, src string) (string, error) {
src = strings.TrimSpace(src)
ext := strings.ToLower(filepath.Ext(src))
if !askOperatorImageExt[ext] {
@@ -182,34 +183,54 @@ func resolveAskOperatorImage(runDir, src string) (string, error) {
if slices.Contains(strings.Split(filepath.ToSlash(src), "/"), "..") {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
if !filepath.IsAbs(src) {
src = filepath.Join(runDir, src)
var rel string
if filepath.IsAbs(src) {
r, err := filepath.Rel(taskDir, filepath.Clean(src))
if err != nil {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
rel = r
} else {
rel = filepath.Join(runName, src)
}
realRoot, err := filepath.EvalSymlinks(runDir)
if err != nil {
return "", fmt.Errorf("image not readable")
}
real, err := filepath.EvalSymlinks(src)
if err != nil {
return "", fmt.Errorf("image not readable")
}
rel, err := filepath.Rel(realRoot, real)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
if !filepath.IsLocal(rel) || (rel != runName && !strings.HasPrefix(rel, runName+string(filepath.Separator))) {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
return real, nil
return rel, nil
}
// openAskOperatorImage opens the image at path and requires the opened file to be
// the regular file lst describes, lst being the Lstat of path. Between the
// EvalSymlinks of resolveAskOperatorImage and this open, the agent can replace the
// file with a symlink: Lstat does not follow one and the open does, so the two then
// name different files and the image is refused.
func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
// askOperatorRejectSymlinks refuses a symlink in any component of rel below the
// task root. os.Root follows links that stay inside the root, so a link from the
// run directory to a sibling would otherwise be read.
func askOperatorRejectSymlinks(root *os.Root, rel string) error {
parts := strings.Split(rel, string(filepath.Separator))
prefix := parts[0]
for i, part := range parts {
if i > 0 {
prefix = filepath.Join(prefix, part)
}
info, err := root.Lstat(prefix)
if err != nil {
return fmt.Errorf("image not readable")
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("image_path must stay inside the run directory")
}
if i < len(parts)-1 && !info.IsDir() {
return fmt.Errorf("image not readable")
}
}
return nil
}
// openAskOperatorImage opens rel under the task root and requires the opened file
// to be the regular file lst describes. The root refuses a path outside the task
// and a symlink that leaves it; Lstat does not follow the last component.
func openAskOperatorImage(root *os.Root, rel string, lst os.FileInfo) (*os.File, error) {
if !lst.Mode().IsRegular() {
return nil, fmt.Errorf("image_path must be a regular file")
}
f, err := os.Open(path)
f, err := root.Open(rel)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
@@ -220,18 +241,22 @@ func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
return f, nil
}
// askOperatorUploadsDir returns tasks/<id>/uploads, created when absent. A symlink
// or anything else that is not a directory is refused: the copy would be written
// through it.
func askOperatorUploadsDir(taskDir string) (string, error) {
dir := filepath.Join(taskDir, "uploads")
if err := os.Mkdir(dir, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
return "", err
// askOperatorUploadsRoot returns tasks/<id>/uploads as a root anchored at the
// task directory. A symlink or anything else that is not a directory is refused:
// the copy would be written through it.
func askOperatorUploadsRoot(taskRoot *os.Root) (*os.Root, error) {
if err := taskRoot.Mkdir("uploads", 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
return nil, err
}
if fi, err := os.Lstat(dir); err != nil || !fi.IsDir() {
return "", fmt.Errorf("the task uploads directory is not a directory")
fi, err := taskRoot.Lstat("uploads")
if err != nil || fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() {
return nil, fmt.Errorf("the task uploads directory is not a directory")
}
return dir, nil
uploads, err := taskRoot.OpenRoot("uploads")
if err != nil {
return nil, fmt.Errorf("the task uploads directory is not a directory")
}
return uploads, nil
}
// askOperatorStageTries bounds the names tried for one staged copy.
@@ -257,33 +282,57 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
if src == "" {
return nil, nil
}
taskDir := filepath.Join(dataDir, "tasks", strconv.FormatInt(taskID, 10))
resolved, err := resolveAskOperatorImage(agent.EnsureRunDir(dataDir, taskID, intentID), src)
if err != nil {
return nil, err
taskRel := filepath.Join("tasks", strconv.FormatInt(taskID, 10))
runName := "main"
if intentID > 0 {
runName = "i" + strconv.FormatInt(intentID, 10)
}
st, err := os.Lstat(resolved)
// Every lookup is anchored at the task directory: a run directory or an
// intermediate directory swapped for a symlink cannot leave the task.
dataRoot, err := os.OpenRoot(dataDir)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
in, err := openAskOperatorImage(resolved, st)
defer dataRoot.Close()
taskRoot, err := dataRoot.OpenRoot(taskRel)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
defer taskRoot.Close()
runInfo, err := taskRoot.Lstat(runName)
if err != nil || runInfo.Mode()&os.ModeSymlink != 0 || !runInfo.IsDir() {
return nil, fmt.Errorf("image_path must stay inside the run directory")
}
rel, err := askOperatorImageRel(filepath.Join(dataDir, taskRel), runName, src)
if err != nil {
return nil, err
}
if err := askOperatorRejectSymlinks(taskRoot, rel); err != nil {
return nil, err
}
st, err := taskRoot.Lstat(rel)
if err != nil || !st.Mode().IsRegular() {
return nil, fmt.Errorf("image not readable")
}
if st.Size() > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
}
in, err := openAskOperatorImage(taskRoot, rel, st)
if err != nil {
return nil, err
}
defer in.Close()
if st.Size() > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
}
dir, err := askOperatorUploadsDir(taskDir)
uploads, err := askOperatorUploadsRoot(taskRoot)
if err != nil {
return nil, err
}
ext := strings.ToLower(filepath.Ext(resolved))
defer uploads.Close()
ext := strings.ToLower(filepath.Ext(rel))
var name string
var out *os.File
for try := 1; ; try++ {
name = askOperatorStageName(ext)
out, err = os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
out, err = uploads.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
if err == nil {
break
}
@@ -291,9 +340,23 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
return nil, err
}
}
defer out.Close()
if _, err := io.Copy(out, in); err != nil {
committed := false
defer func() {
if !committed {
_ = out.Close()
_ = uploads.Remove(name)
}
}()
n, err := io.Copy(out, io.LimitReader(in, askOperatorMaxImage+1))
if err != nil {
return nil, err
}
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: st.Size()}}, nil
if n > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(n))
}
if err := out.Close(); err != nil {
return nil, err
}
committed = true
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: n}}, nil
}
+76 -7
View File
@@ -282,16 +282,22 @@ func TestStageAskOperatorImageNeverOverwrites(t *testing.T) {
// elsewhere.
func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
root, err := os.OpenRoot(taskDir)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = root.Close() })
src := filepath.Join(taskDir, "i3", "shot.png")
rel := filepath.Join("i3", "shot.png")
outside := filepath.Join(dir, "outside.png")
if err := os.WriteFile(outside, []byte("outside"), 0o644); err != nil {
t.Fatal(err)
}
lst, err := os.Lstat(src)
lst, err := root.Lstat(rel)
if err != nil {
t.Fatal(err)
}
f, err := openAskOperatorImage(src, lst)
f, err := openAskOperatorImage(root, rel, lst)
if err != nil {
t.Fatalf("unchanged file: %v", err)
}
@@ -305,32 +311,95 @@ func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
if err := os.Rename(other, src); err != nil {
t.Fatal(err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened a file that replaced the checked one")
}
// A symlink to a file outside the run directory takes the path.
// A symlink to a file outside the run directory takes the path. os.Root
// refuses the absolute target because it leaves the task root.
if err := os.Remove(src); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, src); err != nil {
t.Skipf("no symlink here: %v", err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened the target of a symlink that replaced the checked file")
}
// The swap came before the Lstat: the last component is a symlink.
if lst, err = os.Lstat(src); err != nil {
if lst, err = root.Lstat(rel); err != nil {
t.Fatal(err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened a path whose last component is a symlink")
}
}
// A run directory replaced by a symlink must not turn the task root into the
// confinement root: the read stays anchored at tasks/<id>.
func TestStageAskOperatorImageRejectsRunDirSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
runDir := filepath.Join(taskDir, "i3")
moved := filepath.Join(taskDir, "i3.real")
if err := os.Rename(runDir, moved); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = os.Remove(runDir)
_ = os.Rename(moved, runDir)
})
if err := os.Symlink("/", runDir); err != nil {
t.Skipf("no symlink here: %v", err)
}
// taskDir/shot.png is outside the run directory but inside the task. With the
// run directory symlinked to /, the old confinement root resolved to / and
// accepted it; the task root must not move.
outsideRun := filepath.Join(taskDir, "shot.png")
if err := os.WriteFile(outsideRun, []byte("outside the run dir"), 0o644); err != nil {
t.Fatal(err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, outsideRun); err == nil {
t.Fatalf("staged %v through a symlinked run directory", att)
}
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
t.Fatalf("staged %v through a symlinked run directory", att)
}
}
// A symlink inside the run directory must not lead to a sibling run directory.
func TestStageAskOperatorImageRejectsSiblingSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
link := filepath.Join(taskDir, "i3", "sibling")
if err := os.Symlink(filepath.Join("..", "main"), link); err != nil {
t.Skipf("no symlink here: %v", err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, filepath.Join("sibling", "shot.png")); err == nil {
t.Fatalf("staged %v through a sibling symlink", att)
}
}
// uploads/ swapped for a symlink must not redirect the copy outside the task.
func TestStageAskOperatorImageRejectsUploadsSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
outside := t.TempDir()
if err := os.Symlink(outside, filepath.Join(taskDir, "uploads")); err != nil {
t.Skipf("no symlink here: %v", err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
t.Fatalf("staged %v through a symlinked uploads directory", att)
}
entries, err := os.ReadDir(outside)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("wrote %d file(s) outside the task", len(entries))
}
}
// The emitted activity must carry the {text, attachments} Detail shape the
// transcript parser expects, so the operator sees the question with the
// attachment card for the screenshot.
+64 -6
View File
@@ -28,6 +28,11 @@ const (
maxArchiveBytes = int64(1 << 47) // 128 TiB safety ceiling for corrupt headers.
)
// taskArchiveBeforeOpenHook is an optional test hook invoked with the payload-relative
// name of each regular file immediately before writeTaskArchivePackage opens it,
// allowing deterministic TOCTOU regression tests (always nil in production).
var taskArchiveBeforeOpenHook func(name string)
type archiveFileMove struct {
Source string `json:"source"`
Relative string `json:"relative"`
@@ -700,15 +705,24 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
if err != nil {
return 0, 0, "", err
}
// Code running as the executor uid can keep a working directory inside the moved run
// directory and swap a directory for a symlink after it was listed. Walk and open
// through a root anchored at the payload so no lookup can leave it, and check that
// each opened file is the one the walk saw.
root, err := os.OpenRoot(payloadDir)
if err != nil {
return 0, 0, "", err
}
defer root.Close()
tarWriter := tar.NewWriter(encoder)
walkErr := filepath.WalkDir(payloadDir, func(current string, entry fs.DirEntry, walkErr error) error {
walkErr := walkTaskArchiveRoot(root, ".", func(relative string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
relative, err := filepath.Rel(payloadDir, current)
if err != nil || relative == "." {
return err
if relative == "." {
return nil
}
current := filepath.Join(payloadDir, filepath.FromSlash(relative))
info, err := entry.Info()
if err != nil {
return err
@@ -730,7 +744,7 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
if err != nil {
return err
}
header.Name = filepath.ToSlash(relative)
header.Name = relative
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
@@ -738,10 +752,21 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
return nil
}
originalSize += info.Size()
input, err := os.Open(current)
if taskArchiveBeforeOpenHook != nil {
taskArchiveBeforeOpenHook(relative)
}
input, err := root.Open(filepath.FromSlash(relative))
if err != nil {
return err
}
opened, err := input.Stat()
if err == nil && (!opened.Mode().IsRegular() || !os.SameFile(info, opened)) {
err = fmt.Errorf("task archive entry %s changed while it was packed", relative)
}
if err != nil {
_ = input.Close()
return err
}
_, copyErr := io.Copy(tarWriter, input)
closeErr := input.Close()
return errors.Join(copyErr, closeErr)
@@ -780,6 +805,39 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
return originalSize, compressedSize, checksum, nil
}
// walkTaskArchiveRoot walks dir inside root like fs.WalkDir, in lexical order, with
// slash-separated names. It does not go through root.FS(), which refuses names that
// are not valid UTF-8, so a run tree holding such a file can still be archived as
// before. Entries come from ReadDir on a handle opened in root, so their FileInfo is
// read relative to that handle, never through a path that could leave the root.
func walkTaskArchiveRoot(root *os.Root, dir string, fn fs.WalkDirFunc) error {
handle, err := root.Open(filepath.FromSlash(dir))
if err != nil {
return fn(dir, nil, err)
}
entries, err := handle.ReadDir(-1)
_ = handle.Close()
if err != nil {
return fn(dir, nil, err)
}
slices.SortFunc(entries, func(a, b fs.DirEntry) int { return strings.Compare(a.Name(), b.Name()) })
for _, entry := range entries {
name := entry.Name()
if dir != "." {
name = dir + "/" + name
}
if err := fn(name, entry, nil); err != nil {
return err
}
if entry.IsDir() {
if err := walkTaskArchiveRoot(root, name, fn); err != nil {
return err
}
}
}
return nil
}
func extractTaskArchivePackage(path, expectedSHA, destination string) error {
file, err := os.Open(path)
if err != nil {
+339
View File
@@ -0,0 +1,339 @@
//go:build unix
package server
import (
"archive/tar"
"bytes"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
pgdb "github.com/Autumn-27/artex/db"
"github.com/klauspost/compress/zstd"
)
const archiveOutsideSecret = "root-only secret outside the payload"
// sameSizeAsSecret returns a filler as long as archiveOutsideSecret, so a tar header
// taken from the listed file still matches the bytes read through a swapped path.
func sameSizeAsSecret(fill string) string {
return strings.Repeat(fill, len(archiveOutsideSecret))
}
// archiveSymlinkFixture builds a payload with main/zzz/{a_big,jwt.key} and, next to
// the payload, an outside directory holding jwt.key with archiveOutsideSecret.
func archiveSymlinkFixture(t *testing.T) (payload, outside string) {
t.Helper()
base := t.TempDir()
payload = filepath.Join(base, "payload")
outside = filepath.Join(base, "keys")
for path, body := range map[string]string{
filepath.Join(payload, "main", "zzz", "a_big"): "earlier sibling",
filepath.Join(payload, "main", "zzz", "jwt.key"): sameSizeAsSecret("d"),
filepath.Join(outside, "jwt.key"): archiveOutsideSecret,
} {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
return payload, outside
}
// swapBeforeOpen runs swap once, right before the packer opens the file named at.
func swapBeforeOpen(t *testing.T, at string, swap func() error) {
t.Helper()
taskArchiveBeforeOpenHook = func(name string) {
if name != at {
return
}
taskArchiveBeforeOpenHook = nil
if err := swap(); err != nil {
t.Errorf("swap: %v", err)
}
}
t.Cleanup(func() { taskArchiveBeforeOpenHook = nil })
}
// readArchiveEntries returns the regular file contents of a task archive by name.
func readArchiveEntries(t *testing.T, path string) map[string]string {
t.Helper()
file, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer file.Close()
decoder, err := zstd.NewReader(file)
if err != nil {
t.Fatal(err)
}
defer decoder.Close()
entries := map[string]string{}
tr := tar.NewReader(decoder)
for {
header, err := tr.Next()
if errors.Is(err, io.EOF) {
return entries
}
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(tr)
if err != nil {
t.Fatal(err)
}
entries[header.Name] = string(body)
}
}
// packSwapped writes the archive and fails the test if the outside secret, or the
// content of a file other than the one the walk listed, reached it.
func packSwapped(t *testing.T, payload string, unexpected string) {
t.Helper()
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
if err != nil {
t.Logf("refused: %v", err)
return
}
for name, body := range readArchiveEntries(t, archivePath) {
if strings.Contains(body, unexpected) {
t.Fatalf("archive entry %s holds %q, read through a swapped path", name, body)
}
}
t.Fatal("the archive was written although a path changed under the packer")
}
// A directory swapped for a symlink to an outside directory after it was listed and
// an earlier child packed: its later children must not be read through the link.
func TestTaskArchivePackageDirSwappedForOutsideSymlink(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink(outside, dir)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A regular file swapped for a symlink to an outside file after it was listed.
func TestTaskArchivePackageFileSwappedForOutsideSymlink(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
target := filepath.Join(payload, "main", "zzz", "jwt.key")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Remove(target); err != nil {
return err
}
return os.Symlink(filepath.Join(outside, "jwt.key"), target)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A directory swapped for a relative symlink climbing out with ../ segments.
func TestTaskArchivePackageDirSwappedForDotDotSymlink(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink("../../keys", dir)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A directory swapped for a symlink after its parent was listed but before the walk
// descends into it (outside and ../ targets): listing its children must not leave the
// payload either. The same-file check cannot catch this case, because the children
// would be listed and opened through the same link.
func TestTaskArchivePackageDirSwappedBeforeDescent(t *testing.T) {
for name, link := range map[string]string{"outside": "", "dotdot": "../../keys"} {
t.Run(name, func(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
if err := os.WriteFile(filepath.Join(payload, "main", "a_first"), []byte("earlier file"), 0o600); err != nil {
t.Fatal(err)
}
target := link
if target == "" {
target = outside
}
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/a_first", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink(target, dir)
})
packSwapped(t, payload, archiveOutsideSecret)
})
}
}
// A directory swapped for a symlink that stays inside the payload: the file opened
// is not the one the walk listed, so it is refused rather than packed under the
// listed name.
func TestTaskArchivePackageDirSwappedForInsideSymlink(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
other := filepath.Join(payload, "main", "other")
if err := os.MkdirAll(other, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(other, "jwt.key"), []byte(sameSizeAsSecret("o")), 0o600); err != nil {
t.Fatal(err)
}
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink("other", dir)
})
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
if err == nil {
got := readArchiveEntries(t, archivePath)["main/zzz/jwt.key"]
t.Fatalf("archive written with main/zzz/jwt.key = %q after the directory was swapped", got)
}
t.Logf("refused: %v", err)
}
// Symlinks already present to an outside file and an outside directory are skipped:
// neither the file nor the directory's children are packed.
func TestTaskArchivePackageSkipsOutsideSymlinks(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
if err := os.Symlink(filepath.Join(outside, "jwt.key"), filepath.Join(payload, "main", "key-link")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(payload, "main", "keys-link")); err != nil {
t.Fatal(err)
}
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
t.Fatalf("archive should skip symlinks, not fail: %v", err)
}
entries := readArchiveEntries(t, archivePath)
for name, body := range entries {
if strings.Contains(body, archiveOutsideSecret) || strings.HasPrefix(name, "main/key") {
t.Fatalf("outside symlink packed as %s = %q", name, body)
}
}
if entries["main/zzz/jwt.key"] != sameSizeAsSecret("d") {
t.Fatalf("regular file not packed: %q", entries["main/zzz/jwt.key"])
}
}
// File and directory names that are not valid UTF-8 are packed as before: a run tree
// may hold them (tool output, extracted target data), and refusing them would make
// the task impossible to archive.
func TestTaskArchivePackageKeepsNonUTF8Names(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "\xfe-dir")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
for _, path := range []string{filepath.Join(payload, "main", "\xff\xfe.txt"), filepath.Join(dir, "inner.txt")} {
if err := os.WriteFile(path, []byte("body"), 0o600); err != nil {
t.Fatal(err)
}
}
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
t.Fatalf("archive with non-UTF-8 names failed: %v", err)
}
entries := readArchiveEntries(t, archivePath)
for _, name := range []string{"main/\xff\xfe.txt", "main/\xfe-dir/inner.txt"} {
if entries[name] != "body" {
t.Fatalf("entry %q = %q, want body", name, entries[name])
}
}
}
// Restoring never creates a link or writes outside the destination: a symlink or hard
// link entry followed by a regular entry written through it, and nested ../ names.
func TestTaskArchiveExtractRefusesLinksAndNestedTraversal(t *testing.T) {
type entry struct {
header tar.Header
body string
}
reg := func(name string) entry {
return entry{tar.Header{Name: name, Mode: 0o600, Size: 5, Typeflag: tar.TypeReg}, "pwned"}
}
cases := map[string][]entry{
"symlink then write through it": {
{header: tar.Header{Name: "link", Linkname: "OUTSIDE", Typeflag: tar.TypeSymlink, Mode: 0o777}},
reg("link/pwned"),
},
"hard link then write through it": {
{header: tar.Header{Name: "link", Linkname: "OUTSIDE/pwned", Typeflag: tar.TypeLink, Mode: 0o600}},
reg("link"),
},
"nested dotdot": {reg("a/../../pwned")},
"deep nested dotdot": {reg("a/b/../../../pwned")},
"dotdot after directory": {{header: tar.Header{Name: "a/", Typeflag: tar.TypeDir, Mode: 0o700}}, reg("a/../../pwned")},
}
for name, entries := range cases {
t.Run(name, func(t *testing.T) {
base := t.TempDir()
outside := filepath.Join(base, "outside")
if err := os.MkdirAll(outside, 0o755); err != nil {
t.Fatal(err)
}
var compressed bytes.Buffer
encoder, err := zstd.NewWriter(&compressed)
if err != nil {
t.Fatal(err)
}
tw := tar.NewWriter(encoder)
for _, e := range entries {
header := e.header
header.Linkname = strings.ReplaceAll(header.Linkname, "OUTSIDE", outside)
if err := tw.WriteHeader(&header); err != nil {
t.Fatal(err)
}
if e.body != "" {
if _, err := tw.Write([]byte(e.body)); err != nil {
t.Fatal(err)
}
}
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
if err := encoder.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(base, "malicious.tar.zst")
if err := os.WriteFile(path, compressed.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
destination := filepath.Join(base, "restore", "dest")
if err := extractTaskArchivePackage(path, "", destination); err == nil {
t.Fatal("unsafe archive was accepted")
}
for _, escaped := range []string{
filepath.Join(outside, "pwned"),
filepath.Join(base, "restore", "pwned"),
filepath.Join(base, "pwned"),
} {
if _, err := os.Lstat(escaped); !os.IsNotExist(err) {
t.Fatalf("extraction wrote %s: %v", escaped, err)
}
}
if _, err := os.Lstat(filepath.Join(destination, "link")); !os.IsNotExist(err) {
t.Fatalf("extraction created a link entry: %v", err)
}
})
}
}