From a29748591ed4eadd536e41cba3acfc2b92770f9e Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 17 Nov 2026 18:20:38 +0100 Subject: [PATCH 1/7] confinement root --- internal/app/archive/archiver.go | 13 +- internal/app/archive/confine_unix_test.go | 475 ++++++++++ internal/app/archive/create.go | 26 +- internal/app/archive/extract.go | 32 +- internal/app/di/internal/definitions/grpc.go | 8 +- internal/app/fsutil/confine.go | 248 +++++ internal/app/fsutil/confine_test.go | 381 ++++++++ internal/app/fsutil/confine_unix_test.go | 286 ++++++ internal/app/fsutil/path.go | 9 +- internal/app/fsutil/rename.go | 41 + internal/app/fsutil/rename_test.go | 221 +++++ internal/app/fsutil/rename_unix.go | 35 + internal/app/fsutil/rename_unix_test.go | 120 +++ internal/app/fsutil/rename_windows.go | 9 + internal/app/grpc/archive_handler.go | 17 +- internal/app/grpc/client.go | 8 + .../app/grpc/file_confinement_unix_test.go | 858 ++++++++++++++++++ internal/app/grpc/file_handler.go | 323 ++++--- .../grpc/transfer_confinement_unix_test.go | 281 ++++++ internal/app/grpc/transfer_handler.go | 43 +- .../app/repositories/server_repository.go | 15 + .../repositories/server_repository_test.go | 54 ++ 22 files changed, 3306 insertions(+), 197 deletions(-) create mode 100644 internal/app/archive/confine_unix_test.go create mode 100644 internal/app/fsutil/confine.go create mode 100644 internal/app/fsutil/confine_test.go create mode 100644 internal/app/fsutil/confine_unix_test.go create mode 100644 internal/app/fsutil/rename.go create mode 100644 internal/app/fsutil/rename_test.go create mode 100644 internal/app/fsutil/rename_unix.go create mode 100644 internal/app/fsutil/rename_unix_test.go create mode 100644 internal/app/fsutil/rename_windows.go create mode 100644 internal/app/grpc/file_confinement_unix_test.go create mode 100644 internal/app/grpc/transfer_confinement_unix_test.go create mode 100644 internal/app/repositories/server_repository_test.go diff --git a/internal/app/archive/archiver.go b/internal/app/archive/archiver.go index 991d1b0..59400dc 100644 --- a/internal/app/archive/archiver.go +++ b/internal/app/archive/archiver.go @@ -1,10 +1,13 @@ // Package archive creates and extracts archives (zip, tar family, single-file // compression, 7z, rar) on behalf of API requests. Every caller-supplied path -// is resolved with fsutil.RootRel and accessed through an *os.Root opened at -// the work directory, so no operation can escape the work directory — os.Root -// refuses symlink and ".." resolution outside of it. Extracted archive entries -// are additionally rejected lexically when their path is absolute or starts -// with ".." (zip-slip), because the API contract requires the friendly error. +// is placed by an fsutil.Confiner and accessed through the *os.Root it opens: +// at the game server directory the path belongs to, or at the work directory +// for a path outside every game server. No operation can leave that directory +// — os.Root refuses symlink and ".." resolution outside of it — so a link in +// one game server cannot pull a neighbour's files into an archive or unpack an +// archive over them. Extracted archive entries are additionally rejected +// lexically when their path is absolute or starts with ".." (zip-slip), +// because the API contract requires the friendly error. // // Extraction feeds attacker-controlled bytes to third-party format decoders, // so the caller is expected to run it under a recover (see the gRPC archive diff --git a/internal/app/archive/confine_unix_test.go b/internal/app/archive/confine_unix_test.go new file mode 100644 index 0000000..ac3bdee --- /dev/null +++ b/internal/app/archive/confine_unix_test.go @@ -0,0 +1,475 @@ +//go:build linux || darwin + +package archive + +import ( + "archive/zip" + "context" + "os" + "path/filepath" + "testing" + + "github.com/gameap/daemon/internal/app/fsutil" + pb "github.com/gameap/gameap/pkg/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type knownServerDirs []string + +func (d knownServerDirs) ServerDirs() []string { + return d +} + +// tenantWorkDir lays out a node with two game servers; the directory of server +// "a" holds the symlinks its tenant can create from inside the game process. +func tenantWorkDir(t *testing.T) string { + t.Helper() + + workDir := t.TempDir() + + writeTree(t, workDir, map[string]string{ + "servers/a/own.txt": "own", + "servers/a/cstrike/server.cfg": "hostname a", + "servers/b/victim.txt": "victim", + "servers/b/cstrike/server.cfg": "rcon_password secret", + "steamcmd/steamcmd.sh": "#!/bin/sh", + }) + + for name, target := range map[string]string{ + "servers-link": "..", + "node-link": "../..", + "file-link": "../b/cstrike/server.cfg", + "in-link": "cstrike", + } { + require.NoError(t, os.Symlink(target, filepath.Join(workDir, "servers", "a", name))) + } + + return workDir +} + +// confinementModes are the two ways a request ends up confined to server "a": +// the daemon knows the game server directories, or the panel names the root. +func confinementModes() map[string][]fsutil.ConfineOption { + return map[string][]fsutil.ConfineOption{ + "known_server_dirs": {fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})}, + "request_root": {fsutil.WithRoot("servers/a")}, + } +} + +func zipEntryNames(t *testing.T, path string) []string { + t.Helper() + + r, err := zip.OpenReader(path) + require.NoError(t, err) + defer r.Close() + + names := make([]string, 0, len(r.File)) + for _, f := range r.File { + names = append(names, f.Name) + } + + return names +} + +func TestCreate_Confinement(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + params *pb.CreateArchiveParams + wantError string + // wantEntries is checked when the archive is expected to be created. + wantEntries []string + }{ + { + name: "own_tree_keeps_links_as_links", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/backup.zip", + BasePath: "servers/a", + Sources: []string{"."}, + }, + wantEntries: []string{ + "own.txt", "cstrike/", "cstrike/server.cfg", "servers-link", "node-link", "file-link", "in-link", + }, + }, + { + name: "own_tree_following_a_link_that_stays_inside", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/backup.zip", + BasePath: "servers/a", + Sources: []string{"in-link"}, + FollowSymlinks: true, + }, + wantEntries: []string{"in-link/", "in-link/server.cfg"}, + }, + { + name: "following_a_link_to_the_parent", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/backup.zip", + BasePath: "servers/a", + Sources: []string{"servers-link"}, + FollowSymlinks: true, + }, + wantError: "path escapes from parent", + }, + { + name: "following_a_link_to_a_neighbour_file", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/backup.zip", + BasePath: "servers/a", + Sources: []string{"file-link"}, + FollowSymlinks: true, + }, + wantError: "path escapes from parent", + }, + { + name: "whole_tree_following_links", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/backup.zip", + BasePath: "servers/a", + Sources: []string{"."}, + FollowSymlinks: true, + }, + wantError: "path escapes from parent", + }, + { + name: "source_named_through_a_link", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/backup.zip", + BasePath: "servers/a", + Sources: []string{"servers-link/b/cstrike/server.cfg"}, + }, + wantError: "path escapes from parent", + }, + { + name: "base_path_named_through_a_link", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/backup.zip", + BasePath: "servers/a/servers-link/b", + Sources: []string{"."}, + }, + wantError: "path escapes from parent", + }, + { + name: "archive_written_through_a_link", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/servers-link/b/planted.zip", + BasePath: "servers/a", + Sources: []string{"own.txt"}, + }, + wantError: "path escapes from parent", + }, + { + name: "archive_written_over_a_node_file_through_a_link", + params: &pb.CreateArchiveParams{ + ArchivePath: "servers/a/node-link/steamcmd/steamcmd.sh", + Format: pb.ArchiveFormat_ARCHIVE_FORMAT_ZIP, + BasePath: "servers/a", + Sources: []string{"own.txt"}, + Overwrite: true, + }, + wantError: "path escapes from parent", + }, + } + + for modeName, opts := range confinementModes() { + for _, tt := range tests { + t.Run(modeName+"/"+tt.name, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + neighbour := readTree(t, filepath.Join(workDir, "servers", "b")) + node := readTree(t, filepath.Join(workDir, "steamcmd")) + + res, err := Create(context.Background(), workDir, tt.params, nil, opts...) + + assert.Equal(t, neighbour, readTree(t, filepath.Join(workDir, "servers", "b"))) + assert.Equal(t, node, readTree(t, filepath.Join(workDir, "steamcmd"))) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + + _, statErr := os.Lstat(filepath.Join(workDir, "servers", "a", "backup.zip")) + assert.ErrorIs(t, statErr, os.ErrNotExist, "a refused operation leaves no archive behind") + + return + } + + require.NoError(t, err) + assert.ElementsMatch( + t, tt.wantEntries, zipEntryNames(t, filepath.Join(workDir, "servers", "a", "backup.zip")), + ) + }) + } + } +} + +func TestExtract_Confinement(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + entries []zipEntry + params *pb.ExtractArchiveParams + wantError string + // wantFiles are the regular files expected below the directory of + // server "a" once the archive is unpacked. + wantFiles map[string]string + }{ + { + name: "into_own_directory", + entries: []zipEntry{{name: "addons/plugin.cfg", mode: 0o644, body: "cfg"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/a/unpacked", + CreateDestination: true, + }, + wantFiles: map[string]string{"unpacked/addons/plugin.cfg": "cfg"}, + }, + { + name: "into_own_directory_behind_a_link_staying_inside", + entries: []zipEntry{{name: "motd.txt", mode: 0o644, body: "motd"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/a/in-link", + }, + wantFiles: map[string]string{"cstrike/motd.txt": "motd"}, + }, + { + name: "destination_named_through_a_link", + entries: []zipEntry{{name: "planted.txt", mode: 0o644, body: "x"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/a/servers-link/b/unpacked", + CreateDestination: true, + }, + wantError: "path escapes from parent", + }, + { + name: "destination_is_a_link_to_the_node", + entries: []zipEntry{{name: "steamcmd/steamcmd.sh", mode: 0o755, body: "id > /tmp/pwned"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/a/node-link", + ConflictPolicy: pb.ArchiveConflictPolicy_ARCHIVE_CONFLICT_POLICY_OVERWRITE, + }, + wantError: "path escapes from parent", + }, + { + name: "entry_unpacked_through_a_link_standing_in_the_destination", + entries: []zipEntry{{name: "servers-link/b/cstrike/server.cfg", mode: 0o644, body: "rcon_password owned"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/a", + ConflictPolicy: pb.ArchiveConflictPolicy_ARCHIVE_CONFLICT_POLICY_OVERWRITE, + }, + wantError: "path escapes from parent", + }, + { + name: "entry_unpacked_over_a_node_file_through_a_link", + entries: []zipEntry{{name: "node-link/steamcmd/steamcmd.sh", mode: 0o755, body: "id > /tmp/pwned"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/a", + ConflictPolicy: pb.ArchiveConflictPolicy_ARCHIVE_CONFLICT_POLICY_OVERWRITE, + }, + wantError: "path escapes from parent", + }, + { + name: "link_entry_pointing_at_the_neighbour", + entries: []zipEntry{{name: "escape", mode: os.ModeSymlink | 0o777, body: "../b"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/a", + }, + wantError: "symlink target escapes the destination", + }, + { + name: "archive_read_through_a_link", + entries: []zipEntry{{name: "x.txt", mode: 0o644, body: "x"}}, + params: &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/servers-link/b/victim.txt", + Destination: "servers/a/unpacked", + Format: pb.ArchiveFormat_ARCHIVE_FORMAT_GZ, + CreateDestination: true, + }, + wantError: "path escapes from parent", + }, + } + + for modeName, opts := range confinementModes() { + for _, tt := range tests { + t.Run(modeName+"/"+tt.name, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + buildZipModes(t, filepath.Join(workDir, "servers", "a", "in.zip"), tt.entries) + + neighbour := readTree(t, filepath.Join(workDir, "servers", "b")) + node := readTree(t, filepath.Join(workDir, "steamcmd")) + + res, err := Extract(context.Background(), workDir, tt.params, nil, opts...) + + assert.Equal(t, neighbour, readTree(t, filepath.Join(workDir, "servers", "b"))) + assert.Equal(t, node, readTree(t, filepath.Join(workDir, "steamcmd"))) + + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, res) + + _, statErr := os.Lstat(filepath.Join(workDir, "servers", "a", "escape")) + assert.ErrorIs(t, statErr, os.ErrNotExist, "an escaping link is not left on disk") + + return + } + + require.NoError(t, err) + + for name, want := range tt.wantFiles { + content, readErr := os.ReadFile(filepath.Join(workDir, "servers", "a", filepath.FromSlash(name))) + require.NoError(t, readErr, name) + assert.Equal(t, want, string(content), name) + } + }) + } + } +} + +func TestArchive_PathOutsideTheRequestRoot(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + buildZip(t, filepath.Join(workDir, "servers", "a", "in.zip"), map[string]string{"x.txt": "x"}) + + const wantError = "path is outside its confinement root" + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "servers/a/leak.zip", + BasePath: "servers/b", + Sources: []string{"."}, + }, nil, fsutil.WithRoot("servers/a")) + require.Error(t, err) + assert.Equal(t, wantError, err.Error()) + + _, err = Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "servers/b/planted.zip", + BasePath: "servers/a", + Sources: []string{"."}, + }, nil, fsutil.WithRoot("servers/a")) + require.Error(t, err) + assert.Equal(t, wantError, err.Error()) + + _, err = Extract(context.Background(), workDir, &pb.ExtractArchiveParams{ + ArchivePath: "servers/a/in.zip", + Destination: "servers/b", + }, nil, fsutil.WithRoot("servers/a")) + require.Error(t, err) + assert.Equal(t, wantError, err.Error()) + + _, err = Extract(context.Background(), workDir, &pb.ExtractArchiveParams{ + ArchivePath: "steamcmd/steamcmd.sh", + Destination: "servers/a", + }, nil, fsutil.WithRoot("servers/a")) + require.Error(t, err) + assert.Equal(t, wantError, err.Error()) + + assert.Equal(t, map[string]string{ + "victim.txt": "victim", + "cstrike/server.cfg": "rcon_password secret", + }, readTree(t, filepath.Join(workDir, "servers", "b"))) + + _, statErr := os.Lstat(filepath.Join(workDir, "servers", "a", "leak.zip")) + assert.ErrorIs(t, statErr, os.ErrNotExist) +} + +// A caller acting for the node names no root: the archive and the tree may +// then live in different game server directories, each confined on its own. +func TestArchive_NodeLevelAcrossServerDirs(t *testing.T) { + t.Parallel() + + opts := []fsutil.ConfineOption{fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})} + + t.Run("pack_a_server_into_a_node_directory", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/a.zip", + BasePath: "servers/a", + Sources: []string{"."}, + }, nil, opts...) + + require.NoError(t, err) + assert.ElementsMatch(t, []string{ + "own.txt", "cstrike/", "cstrike/server.cfg", "servers-link", "node-link", "file-link", "in-link", + }, zipEntryNames(t, filepath.Join(workDir, "backups", "a.zip"))) + }) + + t.Run("packing_a_server_does_not_follow_its_links_out", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/a.zip", + BasePath: "servers/a", + Sources: []string{"."}, + FollowSymlinks: true, + }, nil, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + + _, statErr := os.Lstat(filepath.Join(workDir, "backups", "a.zip")) + assert.ErrorIs(t, statErr, os.ErrNotExist) + }) + + t.Run("unpack_a_node_archive_into_a_server", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + writeTree(t, workDir, map[string]string{"backups/.keep": ""}) + buildZipModes(t, filepath.Join(workDir, "backups", "in.zip"), []zipEntry{ + {name: "restored.cfg", mode: 0o644, body: "restored"}, + }) + + _, err := Extract(context.Background(), workDir, &pb.ExtractArchiveParams{ + ArchivePath: "backups/in.zip", + Destination: "servers/b", + }, nil, opts...) + + require.NoError(t, err) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "restored.cfg")) + require.NoError(t, err) + assert.Equal(t, "restored", string(content)) + }) + + t.Run("unpacking_into_a_server_does_not_follow_its_links_out", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + writeTree(t, workDir, map[string]string{"backups/.keep": ""}) + buildZipModes(t, filepath.Join(workDir, "backups", "in.zip"), []zipEntry{ + {name: "node-link/steamcmd/steamcmd.sh", mode: 0o755, body: "id > /tmp/pwned"}, + }) + + _, err := Extract(context.Background(), workDir, &pb.ExtractArchiveParams{ + ArchivePath: "backups/in.zip", + Destination: "servers/a", + ConflictPolicy: pb.ArchiveConflictPolicy_ARCHIVE_CONFLICT_POLICY_OVERWRITE, + }, nil, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + + content, err := os.ReadFile(filepath.Join(workDir, "steamcmd", "steamcmd.sh")) + require.NoError(t, err) + assert.Equal(t, "#!/bin/sh", string(content)) + }) +} diff --git a/internal/app/archive/create.go b/internal/app/archive/create.go index 61d20e5..68766e9 100644 --- a/internal/app/archive/create.go +++ b/internal/app/archive/create.go @@ -29,7 +29,13 @@ func (e sourceEntry) isSymlink() bool { // Create packs the requested sources into archive_path. See the package doc // for the confinement model. -func Create(ctx context.Context, workDir string, p *pb.CreateArchiveParams, progress ProgressFunc) (*Result, error) { +func Create( + ctx context.Context, + workDir string, + p *pb.CreateArchiveParams, + progress ProgressFunc, + confineOpts ...fsutil.ConfineOption, +) (*Result, error) { if err := ctx.Err(); err != nil { return nil, errors.Wrap(err, "create archive canceled") } @@ -38,16 +44,17 @@ func Create(ctx context.Context, workDir string, p *pb.CreateArchiveParams, prog return nil, errors.New("no sources given") } - root, err := os.OpenRoot(workDir) - if err != nil { - return nil, errors.Wrap(err, "work directory unavailable") - } - defer root.Close() + confiner := fsutil.NewConfiner(workDir, confineOpts...) - archiveRel, err := fsutil.RootRel(p.GetArchivePath()) + // The archive file and the tree it is packed from are placed separately: + // they need not belong to the same game server directory. + archive, err := confiner.Resolve(p.GetArchivePath(), fsutil.TargetEntry) if err != nil { return nil, err } + defer archive.Close() + + root, archiveRel := archive.Root, archive.Rel // The proto resolves an unset create format from the target file extension. format := p.GetFormat() @@ -64,10 +71,11 @@ func Create(ctx context.Context, workDir string, p *pb.CreateArchiveParams, prog return nil, err } - baseRel, err := fsutil.RootRel(p.GetBasePath()) + base, err := confiner.Resolve(p.GetBasePath(), fsutil.TargetTree) if err != nil { return nil, err } + defer base.Close() if parent := path.Dir(archiveRel); parent != "." && parent != "/" { if err := root.MkdirAll(parent, 0o755); err != nil { @@ -91,7 +99,7 @@ func Create(ctx context.Context, workDir string, p *pb.CreateArchiveParams, prog acc := newAccumulator(p.GetMaxTotalBytes(), p.GetMaxFiles(), progress) - createErr := createInto(ctx, root, archiveFile, baseRel, p, format, class, acc) + createErr := createInto(ctx, base.Root, archiveFile, base.Rel, p, format, class, acc) closeErr := archiveFile.Close() if createErr != nil { diff --git a/internal/app/archive/extract.go b/internal/app/archive/extract.go index 58730d8..487c331 100644 --- a/internal/app/archive/extract.go +++ b/internal/app/archive/extract.go @@ -254,8 +254,10 @@ func (s *sink) resolveLinkTarget(linkDir, linkTarget string) (string, error) { case "", ".": continue case "..": + // Above the root there is nothing of the destination left: the + // root is the directory the request is confined to. if cur == "." { - return "", errors.New("symlink target escapes the work directory") + return "", errors.New("symlink target escapes the destination") } cur = path.Dir(cur) @@ -445,32 +447,42 @@ func mkdirAllOwned(root *os.Root, rel string, perm os.FileMode, owner osowner.Op // Extract unpacks archive_path into destination. See the package doc for the // confinement model and safeEntryName for the zip-slip rules. -func Extract(ctx context.Context, workDir string, p *pb.ExtractArchiveParams, progress ProgressFunc) (*Result, error) { +func Extract( + ctx context.Context, + workDir string, + p *pb.ExtractArchiveParams, + progress ProgressFunc, + confineOpts ...fsutil.ConfineOption, +) (*Result, error) { if err := ctx.Err(); err != nil { return nil, errors.Wrap(err, "extract archive canceled") } - root, err := os.OpenRoot(workDir) - if err != nil { - return nil, errors.Wrap(err, "work directory unavailable") - } - defer root.Close() + confiner := fsutil.NewConfiner(workDir, confineOpts...) - archiveRel, err := fsutil.RootRel(p.GetArchivePath()) + // The archive file and the tree it is unpacked into are placed separately: + // they need not belong to the same game server directory. + archive, err := confiner.Resolve(p.GetArchivePath(), fsutil.TargetEntry) if err != nil { return nil, err } + defer archive.Close() - destRel, err := fsutil.RootRel(p.GetDestination()) + archiveRel := archive.Rel + + dest, err := confiner.Resolve(p.GetDestination(), fsutil.TargetTree) if err != nil { return nil, err } + defer dest.Close() + + root, destRel := dest.Root, dest.Rel if err := prepareDestination(root, destRel, p); err != nil { return nil, err } - archiveFile, err := root.Open(archiveRel) + archiveFile, err := archive.Root.Open(archiveRel) if err != nil { return nil, errors.Wrapf(err, "failed to open archive %q", p.GetArchivePath()) } diff --git a/internal/app/di/internal/definitions/grpc.go b/internal/app/di/internal/definitions/grpc.go index a65e238..85292f0 100644 --- a/internal/app/di/internal/definitions/grpc.go +++ b/internal/app/di/internal/definitions/grpc.go @@ -3,6 +3,7 @@ package definitions import ( "context" + "github.com/gameap/daemon/internal/app/fsutil" grpcclient "github.com/gameap/daemon/internal/app/grpc" "github.com/gameap/daemon/internal/app/repositories" serversscheduler "github.com/gameap/daemon/internal/app/servers_scheduler" @@ -28,7 +29,7 @@ func CreateGatewayClient(ctx context.Context, c Container, gameStore *grpcclient cfg.WorkPath, ) - fileHandler := grpcclient.NewGRPCFileHandler(cfg.WorkPath) + fileHandler := grpcclient.NewGRPCFileHandler(cfg.WorkPath, fsutil.WithServerDirs(serverRepo)) serverHandler := grpcclient.NewGRPCServerHandler( serverRepo, @@ -62,20 +63,21 @@ func CreateConnectionManager( ) *grpcclient.ConnectionManager { cfg := c.Cfg(ctx) fileTransferClient := CreateFileTransferClient(ctx, c) + serverRepo := c.Repositories().ServerRepository(ctx).(*repositories.ServerRepository) transferHandler := grpcclient.NewGRPCTransferHandler( cfg.WorkPath, fileTransferClient, client, 4, + fsutil.WithServerDirs(serverRepo), ) client.SetTransferHandler(transferHandler) // 0 selects the handler's own default concurrency. - archiveHandler := grpcclient.NewGRPCArchiveHandler(cfg.WorkPath, client, 0) + archiveHandler := grpcclient.NewGRPCArchiveHandler(cfg.WorkPath, client, 0, fsutil.WithServerDirs(serverRepo)) client.SetArchiveHandler(archiveHandler) - serverRepo := c.Repositories().ServerRepository(ctx).(*repositories.ServerRepository) attachHandler := grpcclient.NewGRPCAttachHandler( serverRepo, c.Services().ProcessManager(ctx), diff --git a/internal/app/fsutil/confine.go b/internal/app/fsutil/confine.go new file mode 100644 index 0000000..67c19f1 --- /dev/null +++ b/internal/app/fsutil/confine.go @@ -0,0 +1,248 @@ +package fsutil + +import ( + "os" + "runtime" + "slices" + "strings" + + "github.com/pkg/errors" +) + +// ErrPathOutsideConfinement is returned when a request names a confinement +// root and one of its paths does not lie inside it. The message is kept stable +// because the panel matches on it. +var ErrPathOutsideConfinement = errors.New("path is outside its confinement root") + +// Target says what an operation does with the path it resolves. It only +// matters for a path that is itself a game server directory. +type Target int + +const ( + // TargetEntry is for operations that act on the named entry as such: they + // stat, remove, rename, chmod or create it, or read and write it as a + // file. The entry belongs to the directory holding it, so a game server + // directory named this way is reached from outside and can still be + // removed or renamed. + TargetEntry Target = iota + // TargetTree is for operations that work inside the named directory: they + // list or walk it, or create entries below it. A game server directory + // named this way confines the operation. + TargetTree +) + +// ServerDirLister reports the directories of the game servers the node hosts, +// relative to the work directory. +type ServerDirLister interface { + ServerDirs() []string +} + +// ConfineOption configures a Confiner. +type ConfineOption func(*Confiner) + +// WithServerDirs makes every game server directory a boundary for the paths +// below it. +func WithServerDirs(lister ServerDirLister) ConfineOption { + return func(c *Confiner) { + c.serverDirs = lister + } +} + +// WithRoot sets the confinement root a request names itself. It is a boundary +// of its own next to the game server directories, never a replacement for +// them. An empty root names nothing. +func WithRoot(root string) ConfineOption { + return func(c *Confiner) { + c.root = root + } +} + +// Confiner places request paths inside the directory they must not leave. +// +// The work directory is shared by every game server of the node, and the files +// of one server are written by its tenant. An os.Root opened at the work +// directory keeps a request inside the node, but it follows a symlink from one +// server into another, into the steamcmd or tools directory, or into the files +// the daemon keeps for itself. Confiner therefore opens the root at the +// directory the request belongs to. Two things draw that boundary, and both +// apply: +// +// - the game server directories the daemon knows (WithServerDirs): a path +// below one of them is confined to it, which covers panels that do not +// send a root; +// - the root the request names (WithRoot), which the panel sets to the game +// server directory for everything it does on behalf of that server: a path +// outside of it is refused, and it confines even where the daemon has not +// been told about the server yet. +// +// A request root thus only narrows what the daemon derives on its own. A path +// that neither of them covers is confined to the work directory. +// +// Boundaries nest, and each is reached through the one enclosing it, so it is +// opened fd-relative like any other component: an absolute or escaping symlink +// in its own path is refused, including one the tenant of an outer game server +// puts in place of a directory nested in its own. +type Confiner struct { + workDir string + serverDirs ServerDirLister + root string +} + +// NewConfiner creates a Confiner anchored at workDir. +func NewConfiner(workDir string, opts ...ConfineOption) *Confiner { + c := &Confiner{workDir: workDir} + for _, opt := range opts { + opt(c) + } + + return c +} + +// Confined is a request path placed inside the root it must be accessed through. +type Confined struct { + // Root is opened at Scope. The caller owns it and closes it. + Root *os.Root + // Rel is the path inside Root, in the form RootRel produces. + Rel string + // Scope is the directory Root is opened at, relative to the work directory + // ("." for the work directory itself). + Scope string +} + +func (c *Confined) Close() error { + return c.Root.Close() +} + +// SameRoot reports whether both paths live in one root, so that a single-root +// primitive such as os.Root.Rename can take them together. +func (c *Confined) SameRoot(other *Confined) bool { + return sameDir(c.Scope, other.Scope) +} + +// Resolve places a caller-supplied path. See Confiner for the model. +func (c *Confiner) Resolve(p string, target Target) (*Confined, error) { + rel, err := RootRel(p) + if err != nil { + return nil, err + } + + boundaries, err := c.boundaries(rel, target) + if err != nil { + return nil, err + } + + root, err := os.OpenRoot(c.workDir) + if err != nil { + return nil, errors.Wrap(err, "work directory unavailable") + } + + scope := "." + + for _, dir := range boundaries { + next, err := root.OpenRoot(relativeTo(dir, scope)) + if err != nil { + // A boundary that is not on disk yet holds nothing a tenant could + // have planted: whatever the operation creates below it is created + // by the daemon, from the enclosing root. + if errors.Is(err, os.ErrNotExist) { + break + } + + _ = root.Close() + + return nil, errors.Wrapf(err, "failed to open confinement directory %q", dir) + } + + _ = root.Close() + root, scope = next, dir + } + + return &Confined{Root: root, Rel: relativeTo(rel, scope), Scope: scope}, nil +} + +// boundaries returns the directories that confine rel, outermost first. Each +// is spelled the way rel spells it, so the directory opened is the one the +// request names even where the file system compares names loosely. +func (c *Confiner) boundaries(rel string, target Target) ([]string, error) { + var lengths []int + + if c.root != "" { + root, err := RootRel(c.root) + if err != nil { + return nil, err + } + + switch { + case root == ".": + // The work directory already confines every path. + case sameDir(rel, root): + lengths = append(lengths, len(rel)) + case isBelow(rel, root): + lengths = append(lengths, len(root)) + default: + return nil, ErrPathOutsideConfinement + } + } + + if c.serverDirs != nil { + for _, serverDir := range c.serverDirs.ServerDirs() { + dir, err := RootRel(serverDir) + if err != nil || dir == "." { + continue + } + + switch { + case isBelow(rel, dir): + lengths = append(lengths, len(dir)) + case target == TargetTree && sameDir(rel, dir): + lengths = append(lengths, len(rel)) + } + } + } + + // Every match is a prefix of rel, so ordering by length puts an enclosing + // directory before the one nested in it. + slices.Sort(lengths) + lengths = slices.Compact(lengths) + + dirs := make([]string, 0, len(lengths)) + for _, n := range lengths { + dirs = append(dirs, rel[:n]) + } + + return dirs, nil +} + +// isBelow reports whether rel names something strictly inside dir. +func isBelow(rel, dir string) bool { + if dir == "." { + return rel != "." + } + + if len(rel) <= len(dir) || rel[len(dir)] != '/' { + return false + } + + return sameDir(rel[:len(dir)], dir) +} + +// relativeTo expresses rel, which is base or lies below it, relative to base. +func relativeTo(rel, base string) string { + if base == "." { + return rel + } + + if len(rel) <= len(base) { + return "." + } + + return rel[len(base)+1:] +} + +func sameDir(a, b string) bool { + if runtime.GOOS == "windows" { + return strings.EqualFold(a, b) + } + + return a == b +} diff --git a/internal/app/fsutil/confine_test.go b/internal/app/fsutil/confine_test.go new file mode 100644 index 0000000..395b569 --- /dev/null +++ b/internal/app/fsutil/confine_test.go @@ -0,0 +1,381 @@ +package fsutil + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type serverDirs []string + +func (d serverDirs) ServerDirs() []string { + return d +} + +// confineTree lays out a work directory with two game servers and a directory +// that belongs to the node itself. +func confineTree(t *testing.T) string { + t.Helper() + + workDir := t.TempDir() + + for name, content := range map[string]string{ + "servers/a/own.txt": "own", + "servers/a/sub/inner.txt": "inner", + "servers/a/nested/deep.md": "deep", + "servers/b/secret.cfg": "rcon_password secret", + "servers/ab/other.txt": "other", + "steamcmd/steamcmd.sh": "#!/bin/sh", + } { + p := filepath.Join(workDir, filepath.FromSlash(name)) + require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755)) + require.NoError(t, os.WriteFile(p, []byte(content), 0o644)) + } + + return workDir +} + +func TestConfiner_Resolve(t *testing.T) { + t.Parallel() + + known := serverDirs{"servers/a", "servers/b"} + + tests := []struct { + name string + serverDirs ServerDirLister + root string + path string + target Target + wantScope string + wantRel string + wantError string + }{ + { + name: "path_below_a_server_dir_is_confined_to_it", + serverDirs: known, + path: "servers/a/sub/inner.txt", + wantScope: "servers/a", + wantRel: "sub/inner.txt", + }, + { + name: "absolute_looking_path_is_work_dir_relative", + serverDirs: known, + path: "/servers/a/own.txt", + wantScope: "servers/a", + wantRel: "own.txt", + }, + { + name: "server_dir_as_entry_is_reached_from_outside", + serverDirs: known, + path: "servers/a", + target: TargetEntry, + wantScope: ".", + wantRel: "servers/a", + }, + { + name: "server_dir_as_tree_confines", + serverDirs: known, + path: "servers/a", + target: TargetTree, + wantScope: "servers/a", + wantRel: ".", + }, + { + name: "path_outside_every_server_dir_stays_in_work_dir", + serverDirs: known, + path: "steamcmd/steamcmd.sh", + wantScope: ".", + wantRel: "steamcmd/steamcmd.sh", + }, + { + name: "name_sharing_a_prefix_is_not_the_server_dir", + serverDirs: known, + path: "servers/ab/other.txt", + wantScope: ".", + wantRel: "servers/ab/other.txt", + }, + { + name: "work_dir_itself", + serverDirs: known, + path: "", + target: TargetTree, + wantScope: ".", + wantRel: ".", + }, + { + name: "server_dir_not_on_disk_yet_leaves_the_enclosing_root", + serverDirs: serverDirs{"servers/new"}, + path: "servers/new/cfg/server.cfg", + wantScope: ".", + wantRel: "servers/new/cfg/server.cfg", + }, + { + name: "nested_server_dirs_confine_to_the_innermost", + serverDirs: serverDirs{"servers/a/nested", "servers/a", "servers"}, + path: "servers/a/nested/deep.md", + wantScope: "servers/a/nested", + wantRel: "deep.md", + }, + { + name: "nested_server_dir_missing_keeps_the_outer_one", + serverDirs: serverDirs{"servers/a", "servers/a/absent"}, + path: "servers/a/absent/file.txt", + wantScope: "servers/a", + wantRel: "absent/file.txt", + }, + { + name: "server_dirs_are_normalized", + serverDirs: serverDirs{"/servers/a/", "servers/a"}, + path: "servers/a/own.txt", + wantScope: "servers/a", + wantRel: "own.txt", + }, + { + name: "unusable_server_dirs_are_ignored", + serverDirs: serverDirs{"", ".", "/", "../outside", "servers/a/../.."}, + path: "servers/a/own.txt", + wantScope: ".", + wantRel: "servers/a/own.txt", + }, + { + name: "no_server_dirs_known", + path: "servers/a/own.txt", + wantScope: ".", + wantRel: "servers/a/own.txt", + }, + { + name: "request_root_confines", + root: "servers/a", + path: "servers/a/sub/inner.txt", + wantScope: "servers/a", + wantRel: "sub/inner.txt", + }, + { + name: "request_root_is_normalized", + root: "/servers/a/", + path: "/servers/a/own.txt", + wantScope: "servers/a", + wantRel: "own.txt", + }, + { + name: "request_root_itself_as_entry_stays_inside", + root: "servers/a", + path: "servers/a", + target: TargetEntry, + wantScope: "servers/a", + wantRel: ".", + }, + { + name: "server_dir_inside_the_request_root_still_confines", + serverDirs: known, + root: "servers", + path: "servers/a/own.txt", + wantScope: "servers/a", + wantRel: "own.txt", + }, + { + name: "request_root_inside_a_server_dir_confines_further", + serverDirs: known, + root: "servers/a/nested", + path: "servers/a/nested/deep.md", + wantScope: "servers/a/nested", + wantRel: "deep.md", + }, + { + name: "request_root_matching_the_server_dir", + serverDirs: known, + root: "servers/a", + path: "servers/a/sub/inner.txt", + wantScope: "servers/a", + wantRel: "sub/inner.txt", + }, + { + name: "request_root_itself_as_entry_of_a_known_server_dir_stays_inside", + serverDirs: known, + root: "servers/a", + path: "servers/a", + target: TargetEntry, + wantScope: "servers/a", + wantRel: ".", + }, + { + name: "request_root_of_the_work_dir", + root: "/", + path: "servers/a/own.txt", + wantScope: ".", + wantRel: "servers/a/own.txt", + }, + { + name: "request_root_of_the_work_dir_keeps_the_server_dirs", + serverDirs: known, + root: "/", + path: "servers/a/own.txt", + wantScope: "servers/a", + wantRel: "own.txt", + }, + { + name: "request_root_not_on_disk_yet_keeps_the_enclosing_server_dir", + serverDirs: known, + root: "servers/a/absent", + path: "servers/a/absent/file.txt", + wantScope: "servers/a", + wantRel: "absent/file.txt", + }, + { + name: "request_root_not_on_disk_yet_leaves_the_work_dir", + root: "servers/new", + path: "servers/new/cfg/server.cfg", + wantScope: ".", + wantRel: "servers/new/cfg/server.cfg", + }, + { + name: "path_outside_the_request_root", + serverDirs: known, + root: "servers/a", + path: "servers/b/secret.cfg", + wantError: "path is outside its confinement root", + }, + { + name: "path_above_the_request_root", + root: "servers/a", + path: "servers", + wantError: "path is outside its confinement root", + }, + { + name: "name_sharing_a_prefix_is_outside_the_request_root", + root: "servers/a", + path: "servers/ab/other.txt", + wantError: "path is outside its confinement root", + }, + { + name: "dot_dot_into_the_neighbour_is_outside_the_request_root", + root: "servers/a", + path: "servers/a/../b/secret.cfg", + wantError: "path is outside its confinement root", + }, + { + name: "dot_dot_into_the_neighbour_is_confined_to_the_neighbour", + serverDirs: known, + path: "servers/a/../b/secret.cfg", + wantScope: "servers/b", + wantRel: "secret.cfg", + }, + { + name: "path_escaping_the_work_dir_lexically", + root: "servers/a", + path: "servers/a/../../../etc/passwd", + wantError: "path is outside work directory", + }, + { + name: "request_root_escaping_lexically", + root: "../servers", + path: "servers/a/own.txt", + wantError: "path is outside work directory", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(tt.serverDirs), WithRoot(tt.root)) + + got, err := confiner.Resolve(tt.path, tt.target) + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Nil(t, got) + + return + } + + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, tt.wantScope, got.Scope) + assert.Equal(t, tt.wantRel, got.Rel) + + // The root has to be opened at the directory Scope names: what Rel + // points at is found through it exactly when it is on disk there. + _, rootErr := got.Root.Lstat(got.Rel) + _, diskErr := os.Lstat(filepath.Join(workDir, filepath.FromSlash(got.Scope), filepath.FromSlash(got.Rel))) + assert.Equal(t, diskErr == nil, rootErr == nil) + }) + } +} + +func TestConfiner_Resolve_RootIsOpenedAtScope(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a"})) + + got, err := confiner.Resolve("servers/a/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + content, err := got.Root.ReadFile(got.Rel) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + + _, err = got.Root.Stat("b/secret.cfg") + require.Error(t, err, "a neighbouring server is not below the root") + + _, err = got.Root.Stat("../b/secret.cfg") + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") +} + +func TestConfiner_Resolve_WorkDirUnavailable(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(filepath.Join(t.TempDir(), "absent"), WithServerDirs(serverDirs{"servers/a"})) + + got, err := confiner.Resolve("servers/a/own.txt", TargetEntry) + + require.Error(t, err) + assert.Contains(t, err.Error(), "work directory unavailable") + assert.Nil(t, got) +} + +func TestConfiner_Resolve_ServerDirIsAFile(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a/own.txt"})) + + got, err := confiner.Resolve("servers/a/own.txt/inside", TargetEntry) + + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to open confinement directory "servers/a/own.txt"`) + assert.Nil(t, got) +} + +func TestConfined_SameRoot(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + resolve := func(p string) *Confined { + c, err := confiner.Resolve(p, TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = c.Close() }) + + return c + } + + own := resolve("servers/a/own.txt") + inner := resolve("servers/a/sub/inner.txt") + neighbour := resolve("servers/b/secret.cfg") + node := resolve("steamcmd/steamcmd.sh") + + assert.True(t, own.SameRoot(inner)) + assert.False(t, own.SameRoot(neighbour)) + assert.False(t, own.SameRoot(node)) + assert.True(t, node.SameRoot(resolve("servers/a"))) +} diff --git a/internal/app/fsutil/confine_unix_test.go b/internal/app/fsutil/confine_unix_test.go new file mode 100644 index 0000000..f9952ea --- /dev/null +++ b/internal/app/fsutil/confine_unix_test.go @@ -0,0 +1,286 @@ +//go:build linux || darwin + +package fsutil + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// plantLinks puts into the directory of server "a" the symlinks its tenant can +// create there: some leave the directory, one stays inside it. +func plantLinks(t *testing.T, workDir string) { + t.Helper() + + serverDir := filepath.Join(workDir, "servers", "a") + + for name, target := range map[string]string{ + "servers-link": "..", + "node-link": "../..", + "file-link": "../b/secret.cfg", + "abs-link": filepath.Join(workDir, "servers", "b"), + "in-link": "sub", + } { + require.NoError(t, os.Symlink(target, filepath.Join(serverDir, name))) + } +} + +func TestConfiner_SymlinksOutOfTheServerDirAreRefused(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + serverDirs ServerDirLister + root string + path string + wantError string + }{ + { + name: "neighbour_through_a_link_to_the_parent", + serverDirs: serverDirs{"servers/a", "servers/b"}, + path: "servers/a/servers-link/b/secret.cfg", + wantError: "path escapes from parent", + }, + { + name: "node_files_through_a_link_to_the_work_dir", + serverDirs: serverDirs{"servers/a"}, + path: "servers/a/node-link/steamcmd/steamcmd.sh", + wantError: "path escapes from parent", + }, + { + name: "neighbour_file_through_a_file_link", + serverDirs: serverDirs{"servers/a"}, + path: "servers/a/file-link", + wantError: "path escapes from parent", + }, + { + name: "absolute_link", + serverDirs: serverDirs{"servers/a"}, + path: "servers/a/abs-link/secret.cfg", + wantError: "path escapes from parent", + }, + { + name: "neighbour_through_a_link_with_a_request_root", + root: "servers/a", + path: "servers/a/servers-link/b/secret.cfg", + wantError: "path escapes from parent", + }, + { + name: "node_files_through_a_link_with_a_request_root", + root: "servers/a", + path: "servers/a/node-link/steamcmd/steamcmd.sh", + wantError: "path escapes from parent", + }, + { + name: "link_staying_inside_is_followed", + serverDirs: serverDirs{"servers/a"}, + path: "servers/a/in-link/inner.txt", + }, + { + name: "link_staying_inside_is_followed_with_a_request_root", + root: "servers/a", + path: "servers/a/in-link/inner.txt", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + + confiner := NewConfiner(workDir, WithServerDirs(tt.serverDirs), WithRoot(tt.root)) + + got, err := confiner.Resolve(tt.path, TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/a", got.Scope) + + content, err := got.Root.ReadFile(got.Rel) + if tt.wantError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantError) + assert.Empty(t, content) + + return + } + + require.NoError(t, err) + assert.Equal(t, "inner", string(content)) + }) + } +} + +// Without a boundary the work directory is the only limit, and a link from one +// server into another stays inside it. This is what the confinement closes. +func TestConfiner_WithoutServerDirsALinkReachesTheNeighbour(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + + got, err := NewConfiner(workDir).Resolve("servers/a/servers-link/b/secret.cfg", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + content, err := got.Root.ReadFile(got.Rel) + + require.NoError(t, err) + assert.Equal(t, "rcon_password secret", string(content)) +} + +func TestConfiner_ServerDirBehindASymlink(t *testing.T) { + t.Parallel() + + t.Run("link_inside_the_work_dir_is_followed_and_confines", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + require.NoError(t, os.Symlink("a", filepath.Join(workDir, "servers", "alias"))) + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/alias"})) + + own, err := confiner.Resolve("servers/alias/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = own.Close() }) + + assert.Equal(t, "servers/alias", own.Scope) + + content, err := own.Root.ReadFile(own.Rel) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + + escaping, err := confiner.Resolve("servers/alias/servers-link/b/secret.cfg", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = escaping.Close() }) + + _, err = escaping.Root.ReadFile(escaping.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) + + t.Run("link_out_of_the_work_dir_is_refused", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + outside := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(outside, "passwd"), []byte("TOPSECRET"), 0o644)) + require.NoError(t, os.Symlink(outside, filepath.Join(workDir, "servers", "outside"))) + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/outside"})) + + got, err := confiner.Resolve("servers/outside/passwd", TargetEntry) + + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to open confinement directory "servers/outside"`) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, got) + }) + + t.Run("dangling_link_leaves_the_enclosing_root", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("absent", filepath.Join(workDir, "servers", "dangling"))) + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/dangling"})) + + got, err := confiner.Resolve("servers/dangling/file.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, ".", got.Scope) + assert.Equal(t, "servers/dangling/file.txt", got.Rel) + }) +} + +// The outer tenant owns the directory a nested server lives in, so the nested +// boundary is opened from inside the outer one: a link the outer tenant puts in +// its place cannot carry the request out of the outer directory. That holds +// whether the nested directory is known to the daemon or named by the request. +func TestConfiner_NestedServerDirReplacedByALink(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + serverDirs ServerDirLister + root string + }{ + { + name: "nested_dir_known_to_the_daemon", + serverDirs: serverDirs{"servers/a", "servers/a/nested"}, + }, + { + name: "nested_dir_named_by_the_request", + serverDirs: serverDirs{"servers/a"}, + root: "servers/a/nested", + }, + { + name: "nested_dir_both_known_and_named", + serverDirs: serverDirs{"servers/a", "servers/a/nested"}, + root: "servers/a/nested", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.RemoveAll(filepath.Join(workDir, "servers", "a", "nested"))) + require.NoError(t, os.Symlink("../b", filepath.Join(workDir, "servers", "a", "nested"))) + + confiner := NewConfiner(workDir, WithServerDirs(tt.serverDirs), WithRoot(tt.root)) + + got, err := confiner.Resolve("servers/a/nested/secret.cfg", TargetEntry) + + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to open confinement directory "servers/a/nested"`) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, got) + }) + } +} + +// A request root does not lift the boundary of a game server directory inside +// it: a link there still cannot lead into the rest of the root. +func TestConfiner_RequestRootKeepsTheServerDirBoundary(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + root string + }{ + {name: "root_of_the_work_dir", root: "/"}, + {name: "root_enclosing_the_server_dirs", root: "servers"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"}), WithRoot(tt.root)) + + got, err := confiner.Resolve("servers/a/servers-link/b/secret.cfg", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/a", got.Scope) + + content, err := got.Root.ReadFile(got.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Empty(t, content) + }) + } +} diff --git a/internal/app/fsutil/path.go b/internal/app/fsutil/path.go index b234737..5fbd9dd 100644 --- a/internal/app/fsutil/path.go +++ b/internal/app/fsutil/path.go @@ -1,9 +1,10 @@ // Package fsutil provides path confinement and recursive copy primitives built // on top of Go's os.Root. Every file operation that handles a caller-supplied -// path should resolve it with RootRel and then act through an *os.Root opened -// at the work directory: os.Root resolves each path component through the -// directory fd and refuses symlink / ".." escapes without TOCTOU races, on -// both Linux and Windows. +// path should place it with a Confiner and then act through the *os.Root it +// opens: at the game server directory the path belongs to, or at the work +// directory for a path outside every game server. os.Root resolves each path +// component through the directory fd and refuses symlink / ".." escapes +// without TOCTOU races, on both Linux and Windows. // // The recursive copy reproduces the default behaviour of the recursive-copy // library it replaced (shallow symlinks, source permissions preserved, merge diff --git a/internal/app/fsutil/rename.go b/internal/app/fsutil/rename.go new file mode 100644 index 0000000..18c399e --- /dev/null +++ b/internal/app/fsutil/rename.go @@ -0,0 +1,41 @@ +package fsutil + +import ( + "os" + + "github.com/pkg/errors" +) + +// Rename moves src to dst. Two paths confined to the same directory are +// renamed inside it. Otherwise each side keeps to its own root, so neither can +// be led out of its confinement by a symlink standing in the other. +func Rename(src, dst *Confined) error { + if src.SameRoot(dst) { + return src.Root.Rename(src.Rel, dst.Rel) + } + + return renameAcross(src.Root, src.Rel, dst.Root, dst.Rel) +} + +// moveByCopy moves an entry between two roots where the platform has no rename +// relative to two directory handles. It refuses an existing destination: a +// rename would replace it atomically, and a copy can only merge into it. +func moveByCopy(srcRoot *os.Root, src string, dstRoot *os.Root, dst string) error { + if _, err := dstRoot.Lstat(dst); err == nil { + return &os.LinkError{Op: "rename", Old: src, New: dst, Err: os.ErrExist} + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + + if err := CopyTree(srcRoot, src, dstRoot, dst, CopyOptions{}); err != nil { + _ = dstRoot.RemoveAll(dst) + + return err + } + + if err := srcRoot.RemoveAll(src); err != nil { + return errors.Wrap(err, "failed to remove the source after copying it") + } + + return nil +} diff --git a/internal/app/fsutil/rename_test.go b/internal/app/fsutil/rename_test.go new file mode 100644 index 0000000..4fc840d --- /dev/null +++ b/internal/app/fsutil/rename_test.go @@ -0,0 +1,221 @@ +package fsutil + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func resolveEntry(t *testing.T, confiner *Confiner, p string) *Confined { + t.Helper() + + c, err := confiner.Resolve(p, TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = c.Close() }) + + return c +} + +func TestRename_WithinOneServerDir(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, "servers/a/own.txt"), + resolveEntry(t, confiner, "servers/a/sub/renamed.txt"), + ) + + require.NoError(t, err) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "a", "sub", "renamed.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "a", "own.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestRename_BetweenServerDirs(t *testing.T) { + t.Parallel() + + t.Run("file", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, "servers/a/own.txt"), + resolveEntry(t, confiner, "servers/b/moved.txt"), + ) + + require.NoError(t, err) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "moved.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "a", "own.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + + t.Run("directory_into_a_node_directory", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, "servers/a/sub"), + resolveEntry(t, confiner, "steamcmd/sub"), + ) + + require.NoError(t, err) + + content, err := os.ReadFile(filepath.Join(workDir, "steamcmd", "sub", "inner.txt")) + require.NoError(t, err) + assert.Equal(t, "inner", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "a", "sub")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + + t.Run("whole_server_dir", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, "servers/a"), + resolveEntry(t, confiner, "servers/renamed"), + ) + + require.NoError(t, err) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "renamed", "own.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + }) + + t.Run("missing_source", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, "servers/a/absent.txt"), + resolveEntry(t, confiner, "servers/b/moved.txt"), + ) + + require.ErrorIs(t, err, os.ErrNotExist) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "b", "moved.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + + t.Run("missing_destination_directory", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, "servers/a/own.txt"), + resolveEntry(t, confiner, "servers/b/absent/moved.txt"), + ) + + require.ErrorIs(t, err, os.ErrNotExist) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "a", "own.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + }) +} + +func TestMoveByCopy(t *testing.T) { + t.Parallel() + + openRoots := func(t *testing.T) (string, *os.Root, *os.Root) { + t.Helper() + + workDir := confineTree(t) + + src, err := os.OpenRoot(filepath.Join(workDir, "servers", "a")) + require.NoError(t, err) + t.Cleanup(func() { _ = src.Close() }) + + dst, err := os.OpenRoot(filepath.Join(workDir, "servers", "b")) + require.NoError(t, err) + t.Cleanup(func() { _ = dst.Close() }) + + return workDir, src, dst + } + + t.Run("file", func(t *testing.T) { + t.Parallel() + + workDir, src, dst := openRoots(t) + + require.NoError(t, moveByCopy(src, "own.txt", dst, "moved.txt")) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "moved.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "a", "own.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + + t.Run("directory", func(t *testing.T) { + t.Parallel() + + workDir, src, dst := openRoots(t) + + require.NoError(t, moveByCopy(src, "sub", dst, "moved")) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "moved", "inner.txt")) + require.NoError(t, err) + assert.Equal(t, "inner", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "a", "sub")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + + t.Run("existing_destination_is_kept", func(t *testing.T) { + t.Parallel() + + workDir, src, dst := openRoots(t) + + err := moveByCopy(src, "own.txt", dst, "secret.cfg") + + require.ErrorIs(t, err, os.ErrExist) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "secret.cfg")) + require.NoError(t, err) + assert.Equal(t, "rcon_password secret", string(content)) + + content, err = os.ReadFile(filepath.Join(workDir, "servers", "a", "own.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + }) + + t.Run("missing_source_leaves_no_destination", func(t *testing.T) { + t.Parallel() + + workDir, src, dst := openRoots(t) + + err := moveByCopy(src, "absent.txt", dst, "moved.txt") + + require.ErrorIs(t, err, os.ErrNotExist) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "b", "moved.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) +} diff --git a/internal/app/fsutil/rename_unix.go b/internal/app/fsutil/rename_unix.go new file mode 100644 index 0000000..b6d97ef --- /dev/null +++ b/internal/app/fsutil/rename_unix.go @@ -0,0 +1,35 @@ +//go:build linux || darwin + +package fsutil + +import ( + "os" + "path" + + "golang.org/x/sys/unix" +) + +// renameAcross renames an entry of one root into another. The directory +// holding each name is opened through its own root, which is where symlinks +// are followed and checked; renameat then acts on the two directory entries +// themselves and follows nothing. +func renameAcross(srcRoot *os.Root, src string, dstRoot *os.Root, dst string) error { + srcDir, err := srcRoot.Open(path.Dir(src)) + if err != nil { + return err + } + defer srcDir.Close() + + dstDir, err := dstRoot.Open(path.Dir(dst)) + if err != nil { + return err + } + defer dstDir.Close() + + err = unix.Renameat(int(srcDir.Fd()), path.Base(src), int(dstDir.Fd()), path.Base(dst)) + if err != nil { + return &os.LinkError{Op: "renameat", Old: src, New: dst, Err: err} + } + + return nil +} diff --git a/internal/app/fsutil/rename_unix_test.go b/internal/app/fsutil/rename_unix_test.go new file mode 100644 index 0000000..c44296a --- /dev/null +++ b/internal/app/fsutil/rename_unix_test.go @@ -0,0 +1,120 @@ +//go:build linux || darwin + +package fsutil + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRename_LinksOutOfTheServerDirAreRefused(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + source string + destination string + // untouched lists files that must keep their content. + untouched map[string]string + absent []string + }{ + { + name: "neighbour_file_pulled_through_a_link", + source: "servers/a/servers-link/b/secret.cfg", + destination: "servers/a/stolen.cfg", + untouched: map[string]string{"servers/b/secret.cfg": "rcon_password secret"}, + absent: []string{"servers/a/stolen.cfg"}, + }, + { + name: "own_file_pushed_into_the_neighbour_through_a_link", + source: "servers/a/own.txt", + destination: "servers/a/servers-link/b/planted.txt", + untouched: map[string]string{"servers/a/own.txt": "own"}, + absent: []string{"servers/b/planted.txt"}, + }, + { + name: "node_file_replaced_through_a_link", + source: "servers/a/own.txt", + destination: "servers/a/node-link/steamcmd/steamcmd.sh", + untouched: map[string]string{ + "servers/a/own.txt": "own", + "steamcmd/steamcmd.sh": "#!/bin/sh", + }, + }, + { + name: "between_servers_with_a_link_in_the_destination", + source: "servers/b/secret.cfg", + destination: "servers/a/node-link/steamcmd/steamcmd.sh", + untouched: map[string]string{ + "servers/b/secret.cfg": "rcon_password secret", + "steamcmd/steamcmd.sh": "#!/bin/sh", + }, + }, + { + name: "between_servers_with_a_link_in_the_source", + source: "servers/a/node-link/steamcmd/steamcmd.sh", + destination: "servers/b/taken.sh", + untouched: map[string]string{"steamcmd/steamcmd.sh": "#!/bin/sh"}, + absent: []string{"servers/b/taken.sh"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, tt.source), + resolveEntry(t, confiner, tt.destination), + ) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + + for name, want := range tt.untouched { + content, readErr := os.ReadFile(filepath.Join(workDir, filepath.FromSlash(name))) + require.NoError(t, readErr, name) + assert.Equal(t, want, string(content), name) + } + + for _, name := range tt.absent { + _, statErr := os.Lstat(filepath.Join(workDir, filepath.FromSlash(name))) + assert.ErrorIs(t, statErr, os.ErrNotExist, name) + } + }) + } +} + +// A rename acts on the link itself, so a tenant can still move or rename the +// links standing in their own directory, whatever they point at. +func TestRename_MovesTheLinkItself(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + err := Rename( + resolveEntry(t, confiner, "servers/a/servers-link"), + resolveEntry(t, confiner, "servers/b/moved-link"), + ) + + require.NoError(t, err) + + target, err := os.Readlink(filepath.Join(workDir, "servers", "b", "moved-link")) + require.NoError(t, err) + assert.Equal(t, "..", target) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "a", "servers-link")) + assert.ErrorIs(t, err, os.ErrNotExist) +} diff --git a/internal/app/fsutil/rename_windows.go b/internal/app/fsutil/rename_windows.go new file mode 100644 index 0000000..a0b61d9 --- /dev/null +++ b/internal/app/fsutil/rename_windows.go @@ -0,0 +1,9 @@ +//go:build windows + +package fsutil + +import "os" + +func renameAcross(srcRoot *os.Root, src string, dstRoot *os.Root, dst string) error { + return moveByCopy(srcRoot, src, dstRoot, dst) +} diff --git a/internal/app/grpc/archive_handler.go b/internal/app/grpc/archive_handler.go index d17f233..26be076 100644 --- a/internal/app/grpc/archive_handler.go +++ b/internal/app/grpc/archive_handler.go @@ -2,11 +2,13 @@ package grpc import ( "context" + "slices" "sync" "sync/atomic" "time" daemonarchive "github.com/gameap/daemon/internal/app/archive" + "github.com/gameap/daemon/internal/app/fsutil" pb "github.com/gameap/gameap/pkg/proto" "github.com/pkg/errors" log "github.com/sirupsen/logrus" @@ -45,18 +47,25 @@ type archiveProgressState struct { type GRPCArchiveHandler struct { workDir string + confineOpts []fsutil.ConfineOption responseSender ResponseSender sem *semaphore.Weighted activeArchives sync.Map // map[string]*activeArchive } -func NewGRPCArchiveHandler(workDir string, responseSender ResponseSender, maxConcurrent int64) *GRPCArchiveHandler { +func NewGRPCArchiveHandler( + workDir string, + responseSender ResponseSender, + maxConcurrent int64, + confineOpts ...fsutil.ConfineOption, +) *GRPCArchiveHandler { if maxConcurrent <= 0 { maxConcurrent = defaultMaxConcurrentArchives } return &GRPCArchiveHandler{ workDir: workDir, + confineOpts: confineOpts, responseSender: responseSender, sem: semaphore.NewWeighted(maxConcurrent), } @@ -195,15 +204,17 @@ func (h *GRPCArchiveHandler) run( } }() + confineOpts := append(slices.Clip(h.confineOpts), fsutil.WithRoot(req.GetRoot())) + var result *daemonarchive.Result var err error if create := req.GetCreate(); create != nil { l.WithField("archive_path", create.GetArchivePath()).Info("Creating archive") - result, err = daemonarchive.Create(ctx, h.workDir, create, progressFn) + result, err = daemonarchive.Create(ctx, h.workDir, create, progressFn, confineOpts...) } else { extract := req.GetExtract() l.WithField("archive_path", extract.GetArchivePath()).Info("Extracting archive") - result, err = daemonarchive.Extract(ctx, h.workDir, extract, progressFn) + result, err = daemonarchive.Extract(ctx, h.workDir, extract, progressFn, confineOpts...) } stopProgress() diff --git a/internal/app/grpc/client.go b/internal/app/grpc/client.go index eb5fcc8..1815347 100644 --- a/internal/app/grpc/client.go +++ b/internal/app/grpc/client.go @@ -28,6 +28,13 @@ const ( // own work for the same reason. It sits above their caps because the cheap // metadata operations share this one. maxConcurrentFileOperations = 8 + + // capabilityFileConfinement tells the panel that file, transfer and archive + // requests are confined to the game server directory they belong to, not + // just to the work directory, and that a request may name that directory + // itself. A panel uses it to tell apart daemons that still let a symlink + // lead from one game server into another. + capabilityFileConfinement = "file_confinement" ) type TaskHandler interface { @@ -218,6 +225,7 @@ func (c *GatewayClient) register(ctx context.Context) error { Version: build.Version, Capabilities: []string{ "grpc", "file_transfer", "server_status", "attach", "http_proxy", "metrics", "archive", + capabilityFileConfinement, }, InFlightTasks: inFlightTasks, ServerTaskSnapshotVersion: 0, diff --git a/internal/app/grpc/file_confinement_unix_test.go b/internal/app/grpc/file_confinement_unix_test.go new file mode 100644 index 0000000..69ceaa6 --- /dev/null +++ b/internal/app/grpc/file_confinement_unix_test.go @@ -0,0 +1,858 @@ +//go:build linux || darwin + +package grpc + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/gameap/daemon/internal/app/fsutil" + pb "github.com/gameap/gameap/pkg/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type knownServerDirs []string + +func (d knownServerDirs) ServerDirs() []string { + return d +} + +// tenantWorkDir lays out a node with two game servers. The directory of server +// "a" holds the symlinks its tenant can create from inside the game process: +// into the parent directory, into the work directory, at a neighbour's file, +// and one that stays inside its own directory. +func tenantWorkDir(t *testing.T) string { + t.Helper() + + workDir := t.TempDir() + + for name, content := range map[string]string{ + "servers/a/own.txt": "own", + "servers/a/cstrike/server.cfg": "hostname a", + "servers/a/cstrike/maps/de.bsp": "map", + "servers/b/victim.txt": "victim", + "servers/b/cstrike/server.cfg": "rcon_password secret", + "servers/b/doomed/keep.txt": "keep", + "steamcmd/steamcmd.sh": "#!/bin/sh", + ".plugins/files/users.d/srv.yaml": "password: hunter2", + } { + p := filepath.Join(workDir, filepath.FromSlash(name)) + require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755)) + require.NoError(t, os.WriteFile(p, []byte(content), 0o644)) + } + + serverDir := filepath.Join(workDir, "servers", "a") + + for name, target := range map[string]string{ + "servers-link": "..", + "node-link": "../..", + "file-link": "../b/cstrike/server.cfg", + "users-link": "../../.plugins/files/users.d", + "in-link": "cstrike", + } { + require.NoError(t, os.Symlink(target, filepath.Join(serverDir, name))) + } + + return workDir +} + +// snapshotTree records every entry below dir with its mode and content, so a +// test can prove an operation left it alone. +func snapshotTree(t *testing.T, dir string) map[string]string { + t.Helper() + + snapshot := map[string]string{} + + err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + info, err := d.Info() + if err != nil { + return err + } + + rel, err := filepath.Rel(dir, p) + if err != nil { + return err + } + + entry := info.Mode().String() + if info.Mode().IsRegular() { + content, readErr := os.ReadFile(p) + if readErr != nil { + return readErr + } + + entry += " " + string(content) + } + + snapshot[filepath.ToSlash(rel)] = entry + + return nil + }) + require.NoError(t, err) + + return snapshot +} + +type opResult struct { + success bool + err string +} + +func fileOp( + t *testing.T, h *GRPCFileHandler, root string, op pb.FileOperationType, mutate func(*pb.FileOperationRequest), +) *pb.FileOperationResponse { + t.Helper() + + req := &pb.FileOperationRequest{RequestId: "op", Operation: op, Root: root} + mutate(req) + + resp, err := h.HandleFileOperation(context.Background(), req) + require.NoError(t, err) + + return resp +} + +func opOutcome(resp *pb.FileOperationResponse) opResult { + return opResult{success: resp.GetSuccess(), err: resp.GetError()} +} + +// escapingOperations is every way a tenant of server "a" can ask the daemon to +// reach through one of the planted symlinks. +func escapingOperations(t *testing.T) map[string]func(h *GRPCFileHandler, root string) opResult { + t.Helper() + + ctx := context.Background() + + return map[string]func(h *GRPCFileHandler, root string) opResult{ + "list_neighbours": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileList(ctx, "l", &pb.FileListRequest{Path: "servers/a/servers-link", Root: root}) + require.NoError(t, err) + assert.Empty(t, resp.GetFiles()) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "list_node_recursively": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileList(ctx, "l", &pb.FileListRequest{ + Path: "servers/a/node-link", Recursive: true, Root: root, + }) + require.NoError(t, err) + assert.Empty(t, resp.GetFiles()) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "list_plugin_files": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileList(ctx, "l", &pb.FileListRequest{Path: "servers/a/users-link", Root: root}) + require.NoError(t, err) + assert.Empty(t, resp.GetFiles()) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "read_neighbour_config": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileRead(ctx, "r", &pb.FileReadRequest{ + Path: "servers/a/servers-link/b/cstrike/server.cfg", Root: root, + }) + require.NoError(t, err) + assert.Empty(t, resp.GetContent()) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "read_neighbour_config_range": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileRead(ctx, "r", &pb.FileReadRequest{ + Path: "servers/a/servers-link/b/cstrike/server.cfg", Offset: 5, Length: 8, Root: root, + }) + require.NoError(t, err) + assert.Empty(t, resp.GetContent()) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "read_through_file_link": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileRead(ctx, "r", &pb.FileReadRequest{Path: "servers/a/file-link", Root: root}) + require.NoError(t, err) + assert.Empty(t, resp.GetContent()) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "read_plugin_secret": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileRead(ctx, "r", &pb.FileReadRequest{ + Path: "servers/a/users-link/srv.yaml", Root: root, + }) + require.NoError(t, err) + assert.Empty(t, resp.GetContent()) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "overwrite_steamcmd": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileWrite(ctx, "w", &pb.FileWriteRequest{ + Path: "servers/a/node-link/steamcmd/steamcmd.sh", Content: []byte("id > /tmp/pwned"), Mode: 0o755, + Root: root, + }) + require.NoError(t, err) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "write_into_neighbour_creating_dirs": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileWrite(ctx, "w", &pb.FileWriteRequest{ + Path: "servers/a/servers-link/b/addons/planted.txt", Content: []byte("x"), CreateDirs: true, + Root: root, + }) + require.NoError(t, err) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "overwrite_through_file_link": func(h *GRPCFileHandler, root string) opResult { + resp, err := h.HandleFileWrite(ctx, "w", &pb.FileWriteRequest{ + Path: "servers/a/file-link", Content: []byte("rcon_password owned"), Root: root, + }) + require.NoError(t, err) + + return opResult{resp.GetSuccess(), resp.GetError()} + }, + "stat_neighbour_file": func(h *GRPCFileHandler, root string) opResult { + resp := fileOp(t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_STAT, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_StatParams{ + StatParams: &pb.StatParams{Path: "servers/a/servers-link/b/victim.txt"}, + } + }) + assert.Nil(t, resp.GetStatResult()) + + return opOutcome(resp) + }, + "delete_neighbour_dir": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_DELETE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_DeleteParams{ + DeleteParams: &pb.DeleteParams{Path: "servers/a/servers-link/b/doomed", Recursive: true}, + } + }, + )) + }, + "delete_neighbour_file": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_DELETE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_DeleteParams{ + DeleteParams: &pb.DeleteParams{Path: "servers/a/servers-link/b/victim.txt"}, + } + }, + )) + }, + "steal_neighbour_file": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_MOVE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MoveParams{ + MoveParams: &pb.MoveParams{ + Source: "servers/a/servers-link/b/victim.txt", + Destination: "servers/a/stolen.txt", + }, + } + }, + )) + }, + "move_own_file_into_neighbour": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_MOVE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MoveParams{ + MoveParams: &pb.MoveParams{ + Source: "servers/a/own.txt", + Destination: "servers/a/servers-link/b/planted.txt", + }, + } + }, + )) + }, + "copy_neighbour_config_out": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{ + Source: "servers/a/servers-link/b/cstrike/server.cfg", + Destination: "servers/a/leaked.cfg", + }, + } + }, + )) + }, + "copy_neighbour_tree_out": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{ + Source: "servers/a/servers-link/b", + Destination: "servers/a/leaked", + }, + } + }, + )) + }, + "copy_own_file_into_neighbour": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{ + Source: "servers/a/own.txt", + Destination: "servers/a/servers-link/b/planted.txt", + }, + } + }, + )) + }, + "chmod_neighbour_config": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_CHMOD, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_ChmodParams{ + ChmodParams: &pb.ChmodParams{Path: "servers/a/servers-link/b/cstrike/server.cfg", Mode: 0o777}, + } + }, + )) + }, + "chmod_through_file_link": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_CHMOD, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_ChmodParams{ + ChmodParams: &pb.ChmodParams{Path: "servers/a/file-link", Mode: 0o777}, + } + }, + )) + }, + "chown_neighbour_config": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_CHOWN, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_ChownParams{ + ChownParams: &pb.ChownParams{ + Path: "servers/a/servers-link/b/cstrike/server.cfg", + Uid: int32(os.Getuid()), + Gid: int32(os.Getgid()), + }, + } + }, + )) + }, + "mkdir_in_neighbour": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_MKDIR, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MkdirParams{ + MkdirParams: &pb.MkdirParams{Path: "servers/a/servers-link/b/planted"}, + } + }, + )) + }, + "mkdir_all_in_neighbour": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_MKDIR, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MkdirParams{ + MkdirParams: &pb.MkdirParams{Path: "servers/a/servers-link/b/deep/planted", Recursive: true}, + } + }, + )) + }, + "touch_new_file_in_neighbour": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_TOUCH, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_TouchParams{ + TouchParams: &pb.TouchParams{Path: "servers/a/servers-link/b/planted.txt"}, + } + }, + )) + }, + "touch_neighbour_file": func(h *GRPCFileHandler, root string) opResult { + return opOutcome(fileOp( + t, h, root, pb.FileOperationType_FILE_OPERATION_TYPE_TOUCH, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_TouchParams{ + TouchParams: &pb.TouchParams{Path: "servers/a/servers-link/b/victim.txt"}, + } + }, + )) + }, + } +} + +// confinementModes are the two ways a request ends up confined to server "a": +// the daemon knows the game server directories, or the panel names the root. +func confinementModes() map[string]struct { + opts []fsutil.ConfineOption + root string +} { + return map[string]struct { + opts []fsutil.ConfineOption + root string + }{ + "known_server_dirs": { + opts: []fsutil.ConfineOption{fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})}, + }, + "request_root": { + root: "servers/a", + }, + "request_root_and_known_server_dirs": { + opts: []fsutil.ConfineOption{fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})}, + root: "/servers/a", + }, + } +} + +func TestGRPCFileHandler_SymlinkIntoAnotherServerIsRefused(t *testing.T) { + t.Parallel() + + for modeName, mode := range confinementModes() { + for opName, op := range escapingOperations(t) { + t.Run(modeName+"/"+opName, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + outside := []string{"servers/b", "steamcmd", ".plugins"} + + before := map[string]map[string]string{} + for _, dir := range outside { + before[dir] = snapshotTree(t, filepath.Join(workDir, filepath.FromSlash(dir))) + } + + got := op(NewGRPCFileHandler(workDir, mode.opts...), mode.root) + + assert.False(t, got.success) + assert.Contains(t, got.err, "path escapes from parent") + + for _, dir := range outside { + assert.Equal(t, before[dir], snapshotTree(t, filepath.Join(workDir, filepath.FromSlash(dir))), dir) + } + + for _, name := range []string{"stolen.txt", "leaked.cfg", "leaked"} { + _, err := os.Lstat(filepath.Join(workDir, "servers", "a", name)) + assert.ErrorIs(t, err, os.ErrNotExist, name) + } + }) + } + } +} + +// Before the confinement every one of these went through: the links stay +// inside the work directory, which was the only boundary. +func TestGRPCFileHandler_SymlinkIntoAnotherServerWithoutConfinement(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + h := NewGRPCFileHandler(workDir) + + resp, err := h.HandleFileRead(context.Background(), "r", &pb.FileReadRequest{ + Path: "servers/a/servers-link/b/cstrike/server.cfg", + }) + + require.NoError(t, err) + require.True(t, resp.GetSuccess(), resp.GetError()) + assert.Equal(t, "rcon_password secret", string(resp.GetContent())) +} + +func TestGRPCFileHandler_ExistsDoesNotProbeThroughSymlink(t *testing.T) { + t.Parallel() + + for modeName, mode := range confinementModes() { + t.Run(modeName, func(t *testing.T) { + t.Parallel() + + h := NewGRPCFileHandler(tenantWorkDir(t), mode.opts...) + + exists := func(p string) bool { + resp := fileOp( + t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_EXISTS, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_ExistsParams{ExistsParams: &pb.ExistsParams{Path: p}} + }, + ) + require.True(t, resp.GetSuccess(), resp.GetError()) + + return resp.GetExistsResult().GetExists() + } + + assert.True(t, exists("servers/a/own.txt")) + assert.True(t, exists("servers/a/in-link/server.cfg")) + assert.False(t, exists("servers/a/servers-link/b/victim.txt")) + assert.False(t, exists("servers/a/node-link/steamcmd/steamcmd.sh")) + assert.False(t, exists("servers/a/file-link")) + }) + } +} + +func TestGRPCFileHandler_HashDoesNotReadThroughSymlink(t *testing.T) { + t.Parallel() + + for modeName, mode := range confinementModes() { + t.Run(modeName, func(t *testing.T) { + t.Parallel() + + h := NewGRPCFileHandler(tenantWorkDir(t), mode.opts...) + + resp := fileOp(t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_HASH, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_HashParams{ + HashParams: &pb.HashParams{ + Algorithm: pb.HashAlgorithm_HASH_ALGORITHM_SHA256, + Paths: []string{ + "servers/a/own.txt", + "servers/a/servers-link/b/cstrike/server.cfg", + "servers/a/node-link/steamcmd/steamcmd.sh", + }, + }, + } + }) + + require.True(t, resp.GetSuccess(), resp.GetError()) + + hashes := resp.GetHashResult().GetHashes() + require.Len(t, hashes, 3) + + assert.Equal(t, "servers/a/own.txt", hashes[0].GetPath()) + assert.Empty(t, hashes[0].GetError()) + assert.Equal(t, sha256Hex([]byte("own")), hashes[0].GetHash()) + + for _, refused := range hashes[1:] { + assert.Contains(t, refused.GetError(), "path escapes from parent", refused.GetPath()) + assert.Empty(t, refused.GetHash(), refused.GetPath()) + assert.Zero(t, refused.GetSize(), refused.GetPath()) + } + }) + } +} + +func TestGRPCFileHandler_OwnFilesKeepWorkingWhenConfined(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + for modeName, mode := range confinementModes() { + t.Run(modeName, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + h := NewGRPCFileHandler(workDir, mode.opts...) + serverDir := filepath.Join(workDir, "servers", "a") + + list, err := h.HandleFileList(ctx, "l", &pb.FileListRequest{Path: "servers/a", Root: mode.root}) + require.NoError(t, err) + require.True(t, list.GetSuccess(), list.GetError()) + + listed := map[string]pb.FileType{} + for _, f := range list.GetFiles() { + listed[f.GetPath()] = f.GetType() + } + assert.Equal(t, map[string]pb.FileType{ + "servers/a/own.txt": pb.FileType_FILE_TYPE_REGULAR, + "servers/a/cstrike": pb.FileType_FILE_TYPE_DIRECTORY, + "servers/a/servers-link": pb.FileType_FILE_TYPE_SYMLINK, + "servers/a/node-link": pb.FileType_FILE_TYPE_SYMLINK, + "servers/a/file-link": pb.FileType_FILE_TYPE_SYMLINK, + "servers/a/users-link": pb.FileType_FILE_TYPE_SYMLINK, + "servers/a/in-link": pb.FileType_FILE_TYPE_SYMLINK, + }, listed) + + recursive, err := h.HandleFileList(ctx, "l", &pb.FileListRequest{ + Path: "servers/a/cstrike", Recursive: true, Root: mode.root, + }) + require.NoError(t, err) + require.True(t, recursive.GetSuccess(), recursive.GetError()) + + walked := make([]string, 0, len(recursive.GetFiles())) + for _, f := range recursive.GetFiles() { + walked = append(walked, f.GetPath()) + } + assert.ElementsMatch(t, []string{ + "servers/a/cstrike/server.cfg", + "servers/a/cstrike/maps", + "servers/a/cstrike/maps/de.bsp", + }, walked) + + throughLink, err := h.HandleFileRead(ctx, "r", &pb.FileReadRequest{ + Path: "servers/a/in-link/server.cfg", Root: mode.root, + }) + require.NoError(t, err) + require.True(t, throughLink.GetSuccess(), throughLink.GetError()) + assert.Equal(t, "hostname a", string(throughLink.GetContent())) + + written, err := h.HandleFileWrite(ctx, "w", &pb.FileWriteRequest{ + Path: "servers/a/addons/new/plugin.cfg", Content: []byte("cfg"), CreateDirs: true, Root: mode.root, + }) + require.NoError(t, err) + require.True(t, written.GetSuccess(), written.GetError()) + + content, err := os.ReadFile(filepath.Join(serverDir, "addons", "new", "plugin.cfg")) + require.NoError(t, err) + assert.Equal(t, "cfg", string(content)) + + moved := fileOp(t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_MOVE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MoveParams{ + MoveParams: &pb.MoveParams{Source: "servers/a/own.txt", Destination: "servers/a/cstrike/renamed.txt"}, + } + }) + require.True(t, moved.GetSuccess(), moved.GetError()) + + copied := fileOp(t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{Source: "servers/a/cstrike", Destination: "servers/a/backup"}, + } + }) + require.True(t, copied.GetSuccess(), copied.GetError()) + + content, err = os.ReadFile(filepath.Join(serverDir, "backup", "renamed.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) + + // Removing a planted link removes the link, never what it points at. + unlinked := fileOp( + t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_DELETE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_DeleteParams{ + DeleteParams: &pb.DeleteParams{Path: "servers/a/servers-link", Recursive: true}, + } + }, + ) + require.True(t, unlinked.GetSuccess(), unlinked.GetError()) + + _, err = os.Lstat(filepath.Join(serverDir, "servers-link")) + require.ErrorIs(t, err, os.ErrNotExist) + + content, err = os.ReadFile(filepath.Join(workDir, "servers", "b", "victim.txt")) + require.NoError(t, err) + assert.Equal(t, "victim", string(content)) + + linkStat := fileOp( + t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_STAT, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_StatParams{ + StatParams: &pb.StatParams{Path: "servers/a/node-link"}, + } + }, + ) + require.True(t, linkStat.GetSuccess(), linkStat.GetError()) + assert.Equal(t, pb.FileType_FILE_TYPE_SYMLINK, linkStat.GetStatResult().GetStat().GetType()) + assert.Equal(t, "node-link", linkStat.GetStatResult().GetStat().GetName()) + }) + } +} + +func TestGRPCFileHandler_StatOfTheServerDirKeepsItsName(t *testing.T) { + t.Parallel() + + for modeName, mode := range confinementModes() { + t.Run(modeName, func(t *testing.T) { + t.Parallel() + + h := NewGRPCFileHandler(tenantWorkDir(t), mode.opts...) + + resp := fileOp(t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_STAT, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_StatParams{StatParams: &pb.StatParams{Path: "servers/a"}} + }) + + require.True(t, resp.GetSuccess(), resp.GetError()) + + stat := resp.GetStatResult().GetStat() + assert.Equal(t, "a", stat.GetName()) + assert.Equal(t, "servers/a", stat.GetPath()) + assert.Equal(t, pb.FileType_FILE_TYPE_DIRECTORY, stat.GetType()) + }) + } +} + +func TestGRPCFileHandler_PathOutsideTheRequestRoot(t *testing.T) { + t.Parallel() + + ctx := context.Background() + workDir := tenantWorkDir(t) + h := NewGRPCFileHandler(workDir, fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})) + + const wantError = "path is outside its confinement root" + + read, err := h.HandleFileRead(ctx, "r", &pb.FileReadRequest{Path: "servers/b/victim.txt", Root: "servers/a"}) + require.NoError(t, err) + assert.False(t, read.GetSuccess()) + assert.Equal(t, wantError, read.GetError()) + assert.Empty(t, read.GetContent()) + + list, err := h.HandleFileList(ctx, "l", &pb.FileListRequest{Path: "servers", Root: "servers/a"}) + require.NoError(t, err) + assert.False(t, list.GetSuccess()) + assert.Equal(t, wantError, list.GetError()) + assert.Empty(t, list.GetFiles()) + + write, err := h.HandleFileWrite(ctx, "w", &pb.FileWriteRequest{ + Path: "steamcmd/steamcmd.sh", Content: []byte("x"), Root: "servers/a", + }) + require.NoError(t, err) + assert.False(t, write.GetSuccess()) + assert.Equal(t, wantError, write.GetError()) + + move := fileOp(t, h, "servers/a", pb.FileOperationType_FILE_OPERATION_TYPE_MOVE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MoveParams{ + MoveParams: &pb.MoveParams{Source: "servers/a/own.txt", Destination: "servers/b/planted.txt"}, + } + }) + assert.False(t, move.GetSuccess()) + assert.Equal(t, wantError, move.GetError()) + + content, err := os.ReadFile(filepath.Join(workDir, "steamcmd", "steamcmd.sh")) + require.NoError(t, err) + assert.Equal(t, "#!/bin/sh", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "b", "planted.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +// A caller acting for the node rather than for one server names no root. It +// may work across game server directories, and each half of what it does is +// still confined to the directory it touches. +func TestGRPCFileHandler_NodeLevelOperationsAcrossServerDirs(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + newHandler := func(t *testing.T) (*GRPCFileHandler, string) { + t.Helper() + + workDir := tenantWorkDir(t) + + return NewGRPCFileHandler(workDir, fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})), workDir + } + + t.Run("list_the_directory_holding_the_servers", func(t *testing.T) { + t.Parallel() + + h, _ := newHandler(t) + + resp, err := h.HandleFileList(ctx, "l", &pb.FileListRequest{Path: "servers"}) + require.NoError(t, err) + require.True(t, resp.GetSuccess(), resp.GetError()) + + names := make([]string, 0, len(resp.GetFiles())) + for _, f := range resp.GetFiles() { + names = append(names, f.GetName()) + } + assert.ElementsMatch(t, []string{"a", "b"}, names) + }) + + t.Run("move_between_servers", func(t *testing.T) { + t.Parallel() + + h, workDir := newHandler(t) + + resp := fileOp(t, h, "", pb.FileOperationType_FILE_OPERATION_TYPE_MOVE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MoveParams{ + MoveParams: &pb.MoveParams{Source: "servers/b/victim.txt", Destination: "servers/a/cstrike/moved.txt"}, + } + }) + require.True(t, resp.GetSuccess(), resp.GetError()) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "a", "cstrike", "moved.txt")) + require.NoError(t, err) + assert.Equal(t, "victim", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, "servers", "b", "victim.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + + t.Run("move_between_servers_does_not_follow_a_planted_link", func(t *testing.T) { + t.Parallel() + + h, workDir := newHandler(t) + + resp := fileOp(t, h, "", pb.FileOperationType_FILE_OPERATION_TYPE_MOVE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_MoveParams{ + MoveParams: &pb.MoveParams{ + Source: "servers/b/victim.txt", + Destination: "servers/a/node-link/steamcmd/steamcmd.sh", + }, + } + }) + assert.False(t, resp.GetSuccess()) + assert.Contains(t, resp.GetError(), "path escapes from parent") + + content, err := os.ReadFile(filepath.Join(workDir, "steamcmd", "steamcmd.sh")) + require.NoError(t, err) + assert.Equal(t, "#!/bin/sh", string(content)) + }) + + t.Run("copy_a_server_dir_to_a_new_one", func(t *testing.T) { + t.Parallel() + + h, workDir := newHandler(t) + + resp := fileOp(t, h, "", pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{Source: "servers/a", Destination: "servers/clone"}, + } + }) + require.True(t, resp.GetSuccess(), resp.GetError()) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "clone", "cstrike", "server.cfg")) + require.NoError(t, err) + assert.Equal(t, "hostname a", string(content)) + + // The links are copied as links, not followed into what they point at. + target, err := os.Readlink(filepath.Join(workDir, "servers", "clone", "node-link")) + require.NoError(t, err) + assert.Equal(t, "../..", target) + }) + + t.Run("copy_into_a_server_does_not_follow_a_planted_link", func(t *testing.T) { + t.Parallel() + + h, workDir := newHandler(t) + + resp := fileOp(t, h, "", pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{ + Source: "steamcmd/steamcmd.sh", + Destination: "servers/a/servers-link/b/cstrike/server.cfg", + }, + } + }) + assert.False(t, resp.GetSuccess()) + assert.Contains(t, resp.GetError(), "path escapes from parent") + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "cstrike", "server.cfg")) + require.NoError(t, err) + assert.Equal(t, "rcon_password secret", string(content)) + }) + + t.Run("delete_a_whole_server_dir", func(t *testing.T) { + t.Parallel() + + h, workDir := newHandler(t) + + resp := fileOp(t, h, "", pb.FileOperationType_FILE_OPERATION_TYPE_DELETE, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_DeleteParams{ + DeleteParams: &pb.DeleteParams{Path: "servers/a", Recursive: true}, + } + }) + require.True(t, resp.GetSuccess(), resp.GetError()) + + _, err := os.Lstat(filepath.Join(workDir, "servers", "a")) + require.ErrorIs(t, err, os.ErrNotExist) + + // Removing the tree removed the links in it, not their targets. + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "victim.txt")) + require.NoError(t, err) + assert.Equal(t, "victim", string(content)) + + content, err = os.ReadFile(filepath.Join(workDir, "steamcmd", "steamcmd.sh")) + require.NoError(t, err) + assert.Equal(t, "#!/bin/sh", string(content)) + }) + + t.Run("write_into_a_server_dir_that_is_not_on_disk_yet", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + h := NewGRPCFileHandler(workDir, fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/fresh"})) + + for _, root := range []string{"", "servers/fresh"} { + resp, err := h.HandleFileWrite(ctx, "w", &pb.FileWriteRequest{ + Path: "servers/fresh/cfg/server.cfg", Content: []byte("fresh"), CreateDirs: true, Root: root, + }) + require.NoError(t, err) + require.True(t, resp.GetSuccess(), resp.GetError()) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "fresh", "cfg", "server.cfg")) + require.NoError(t, err) + assert.Equal(t, "fresh", string(content)) + } + }) +} diff --git a/internal/app/grpc/file_handler.go b/internal/app/grpc/file_handler.go index ed42f8f..5141213 100644 --- a/internal/app/grpc/file_handler.go +++ b/internal/app/grpc/file_handler.go @@ -7,6 +7,7 @@ import ( "io/fs" "os" "path" + "slices" "strings" "time" @@ -28,42 +29,43 @@ const ( ) type GRPCFileHandler struct { - workDir string + workDir string + confineOpts []fsutil.ConfineOption } -func NewGRPCFileHandler(workDir string) *GRPCFileHandler { +func NewGRPCFileHandler(workDir string, confineOpts ...fsutil.ConfineOption) *GRPCFileHandler { return &GRPCFileHandler{ - workDir: workDir, + workDir: workDir, + confineOpts: confineOpts, } } -// openRoot opens an os.Root at the work directory. Every path supplied by the -// caller is then resolved through this root, which refuses symlink and ".." -// escapes per path component without TOCTOU races. The root is opened per -// request because workDir is provisioned from the API after construction and -// may not exist yet at startup. -func (h *GRPCFileHandler) openRoot() (*os.Root, error) { - root, err := os.OpenRoot(h.workDir) - if err != nil { - return nil, errors.Wrap(err, "work directory unavailable") - } +// confiner returns the path resolver of one request. Every path supplied by +// the caller goes through it: it is placed inside the game server directory it +// belongs to and accessed through an os.Root opened there, which refuses +// symlink and ".." escapes per path component without TOCTOU races. Roots are +// opened per request because workDir is provisioned from the API after +// construction and may not exist yet at startup. +func (h *GRPCFileHandler) confiner(root string) *fsutil.Confiner { + return requestConfiner(h.workDir, h.confineOpts, root) +} - return root, nil +// requestConfiner completes the confinement a handler was built with by the +// root one request names. +func requestConfiner(workDir string, opts []fsutil.ConfineOption, root string) *fsutil.Confiner { + return fsutil.NewConfiner(workDir, append(slices.Clip(opts), fsutil.WithRoot(root))...) } func (h *GRPCFileHandler) HandleFileRead( _ context.Context, requestID string, req *pb.FileReadRequest, ) (*pb.FileReadResponse, error) { - root, err := h.openRoot() + target, err := h.confiner(req.GetRoot()).Resolve(req.Path, fsutil.TargetEntry) if err != nil { return &pb.FileReadResponse{RequestId: requestID, Success: false, Error: err.Error()}, nil } - defer root.Close() + defer target.Close() - rel, err := fsutil.RootRel(req.Path) - if err != nil { - return &pb.FileReadResponse{RequestId: requestID, Success: false, Error: err.Error()}, nil - } + root, rel := target.Root, target.Rel info, err := root.Stat(rel) if err != nil { @@ -128,16 +130,13 @@ func (h *GRPCFileHandler) HandleFileRead( func (h *GRPCFileHandler) HandleFileWrite( _ context.Context, requestID string, req *pb.FileWriteRequest, ) (*pb.FileWriteResponse, error) { - root, err := h.openRoot() + target, err := h.confiner(req.GetRoot()).Resolve(req.Path, fsutil.TargetEntry) if err != nil { return &pb.FileWriteResponse{RequestId: requestID, Success: false, Error: err.Error()}, nil } - defer root.Close() + defer target.Close() - rel, err := fsutil.RootRel(req.Path) - if err != nil { - return &pb.FileWriteResponse{RequestId: requestID, Success: false, Error: err.Error()}, nil - } + root, rel := target.Root, target.Rel owner := osowner.Options{ User: req.OwnerUser, @@ -196,16 +195,13 @@ func (h *GRPCFileHandler) HandleFileWrite( func (h *GRPCFileHandler) HandleFileList( _ context.Context, requestID string, req *pb.FileListRequest, ) (*pb.FileListResponse, error) { - root, err := h.openRoot() + target, err := h.confiner(req.GetRoot()).Resolve(req.Path, fsutil.TargetTree) if err != nil { return &pb.FileListResponse{RequestId: requestID, Success: false, Error: err.Error()}, nil } - defer root.Close() + defer target.Close() - rel, err := fsutil.RootRel(req.Path) - if err != nil { - return &pb.FileListResponse{RequestId: requestID, Success: false, Error: err.Error()}, nil - } + root, rel := target.Root, target.Rel var files []*pb.FileStat @@ -344,122 +340,119 @@ func (h *GRPCFileHandler) HandleFileOperation( ctx context.Context, req *pb.FileOperationRequest, ) (*pb.FileOperationResponse, error) { rid := req.GetRequestId() - - root, err := h.openRoot() - if err != nil { - return fileOpErrResp(rid, err) - } - defer root.Close() + confiner := h.confiner(req.GetRoot()) switch req.GetOperation() { case pb.FileOperationType_FILE_OPERATION_TYPE_STAT: - p := req.GetStatParams() - if p == nil { - return fileOpErrResp(rid, errors.New("stat_params required")) - } - rel, relErr := fsutil.RootRel(p.GetPath()) - if relErr != nil { - return fileOpErrResp(rid, relErr) - } - info, statErr := root.Lstat(rel) - if statErr != nil { - return fileOpErrResp(rid, statErr) - } - return &pb.FileOperationResponse{ - RequestId: rid, - Success: true, - Result: &pb.FileOperationResponse_StatResult{ - StatResult: &pb.StatResult{ - Stat: fileInfoToStat(p.GetPath(), info), - }, - }, - }, nil + return h.handleStatOp(confiner, rid, req.GetStatParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_EXISTS: - p := req.GetExistsParams() - if p == nil { - return fileOpErrResp(rid, errors.New("exists_params required")) - } - rel, relErr := fsutil.RootRel(p.GetPath()) - if relErr != nil { - return fileOpErrResp(rid, relErr) - } - _, statErr := root.Stat(rel) - return &pb.FileOperationResponse{ - RequestId: rid, - Success: true, - Result: &pb.FileOperationResponse_ExistsResult{ - ExistsResult: &pb.ExistsResult{ - Exists: statErr == nil, - }, - }, - }, nil + return h.handleExistsOp(confiner, rid, req.GetExistsParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_DELETE: - return h.handleDeleteOp(root, rid, req.GetDeleteParams()) + return h.handleDeleteOp(confiner, rid, req.GetDeleteParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_MOVE: - return h.handleMoveOp(root, rid, req.GetMoveParams()) + return h.handleMoveOp(confiner, rid, req.GetMoveParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_COPY: - return h.handleCopyOp(root, rid, req.GetCopyParams()) + return h.handleCopyOp(confiner, rid, req.GetCopyParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_CHMOD: - p := req.GetChmodParams() - if p == nil { - return fileOpErrResp(rid, errors.New("chmod_params required")) - } - rel, relErr := fsutil.RootRel(p.GetPath()) - if relErr != nil { - return fileOpErrResp(rid, relErr) - } - if err := root.Chmod(rel, permMode(p.GetMode())); err != nil { - return fileOpErrResp(rid, err) - } - return fileOpOkResp(rid) + return h.handleChmodOp(confiner, rid, req.GetChmodParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_CHOWN: - p := req.GetChownParams() - if p == nil { - return fileOpErrResp(rid, errors.New("chown_params required")) - } - rel, relErr := fsutil.RootRel(p.GetPath()) - if relErr != nil { - return fileOpErrResp(rid, relErr) - } - if err := root.Chown(rel, int(p.GetUid()), int(p.GetGid())); err != nil { - return fileOpErrResp(rid, err) - } - return fileOpOkResp(rid) + return h.handleChownOp(confiner, rid, req.GetChownParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_MKDIR: - return h.handleMkdirOp(root, rid, req.GetMkdirParams()) + return h.handleMkdirOp(confiner, rid, req.GetMkdirParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_TOUCH: - return h.handleTouchOp(root, rid, req.GetTouchParams()) + return h.handleTouchOp(confiner, rid, req.GetTouchParams()) case pb.FileOperationType_FILE_OPERATION_TYPE_HASH: - return h.handleHashOp(ctx, root, rid, req.GetHashParams()) + return h.handleHashOp(ctx, confiner, rid, req.GetHashParams()) default: return fileOpErrResp(rid, errors.Errorf("unsupported file operation: %s", req.GetOperation())) } } +func (h *GRPCFileHandler) handleStatOp( + confiner *fsutil.Confiner, rid string, p *pb.StatParams, +) (*pb.FileOperationResponse, error) { + if p == nil { + return fileOpErrResp(rid, errors.New("stat_params required")) + } + target, err := confiner.Resolve(p.GetPath(), fsutil.TargetEntry) + if err != nil { + return fileOpErrResp(rid, err) + } + defer target.Close() + + info, err := target.Root.Lstat(target.Rel) + if err != nil { + return fileOpErrResp(rid, err) + } + + stat := fileInfoToStat(p.GetPath(), info) + // The directory a root is opened at has no name inside that root. + if target.Rel == "." && target.Scope != "." { + stat.Name = path.Base(target.Scope) + } + + return &pb.FileOperationResponse{ + RequestId: rid, + Success: true, + Result: &pb.FileOperationResponse_StatResult{ + StatResult: &pb.StatResult{ + Stat: stat, + }, + }, + }, nil +} + +func (h *GRPCFileHandler) handleExistsOp( + confiner *fsutil.Confiner, rid string, p *pb.ExistsParams, +) (*pb.FileOperationResponse, error) { + if p == nil { + return fileOpErrResp(rid, errors.New("exists_params required")) + } + target, err := confiner.Resolve(p.GetPath(), fsutil.TargetEntry) + if err != nil { + return fileOpErrResp(rid, err) + } + defer target.Close() + + _, statErr := target.Root.Stat(target.Rel) + + return &pb.FileOperationResponse{ + RequestId: rid, + Success: true, + Result: &pb.FileOperationResponse_ExistsResult{ + ExistsResult: &pb.ExistsResult{ + Exists: statErr == nil, + }, + }, + }, nil +} + func (h *GRPCFileHandler) handleDeleteOp( - root *os.Root, rid string, p *pb.DeleteParams, + confiner *fsutil.Confiner, rid string, p *pb.DeleteParams, ) (*pb.FileOperationResponse, error) { if p == nil { return fileOpErrResp(rid, errors.New("delete_params required")) } - rel, err := fsutil.RootRel(p.GetPath()) + target, err := confiner.Resolve(p.GetPath(), fsutil.TargetEntry) if err != nil { return fileOpErrResp(rid, err) } + defer target.Close() + if p.GetRecursive() { - err = root.RemoveAll(rel) + err = target.Root.RemoveAll(target.Rel) } else { - err = root.Remove(rel) + err = target.Root.Remove(target.Rel) } if err != nil { return fileOpErrResp(rid, err) @@ -468,55 +461,104 @@ func (h *GRPCFileHandler) handleDeleteOp( } func (h *GRPCFileHandler) handleMoveOp( - root *os.Root, rid string, p *pb.MoveParams, + confiner *fsutil.Confiner, rid string, p *pb.MoveParams, ) (*pb.FileOperationResponse, error) { if p == nil { return fileOpErrResp(rid, errors.New("move_params required")) } - src, err := fsutil.RootRel(p.GetSource()) + src, err := confiner.Resolve(p.GetSource(), fsutil.TargetEntry) if err != nil { return fileOpErrResp(rid, err) } - dst, err := fsutil.RootRel(p.GetDestination()) + defer src.Close() + + dst, err := confiner.Resolve(p.GetDestination(), fsutil.TargetEntry) if err != nil { return fileOpErrResp(rid, err) } - if err := root.Rename(src, dst); err != nil { + defer dst.Close() + + if err := fsutil.Rename(src, dst); err != nil { return fileOpErrResp(rid, err) } return fileOpOkResp(rid) } func (h *GRPCFileHandler) handleCopyOp( - root *os.Root, rid string, p *pb.CopyParams, + confiner *fsutil.Confiner, rid string, p *pb.CopyParams, ) (*pb.FileOperationResponse, error) { if p == nil { return fileOpErrResp(rid, errors.New("copy_params required")) } - src, err := fsutil.RootRel(p.GetSource()) + // A copy reads the source tree and writes the destination tree, so a game + // server directory on either side confines its half of the operation. + src, err := confiner.Resolve(p.GetSource(), fsutil.TargetTree) if err != nil { return fileOpErrResp(rid, err) } - dst, err := fsutil.RootRel(p.GetDestination()) + defer src.Close() + + dst, err := confiner.Resolve(p.GetDestination(), fsutil.TargetTree) if err != nil { return fileOpErrResp(rid, err) } - if err := fsutil.CopyInRoot(root, src, dst, fsutil.CopyOptions{}); err != nil { + defer dst.Close() + + if err := fsutil.CopyTree(src.Root, src.Rel, dst.Root, dst.Rel, fsutil.CopyOptions{}); err != nil { + return fileOpErrResp(rid, err) + } + return fileOpOkResp(rid) +} + +func (h *GRPCFileHandler) handleChmodOp( + confiner *fsutil.Confiner, rid string, p *pb.ChmodParams, +) (*pb.FileOperationResponse, error) { + if p == nil { + return fileOpErrResp(rid, errors.New("chmod_params required")) + } + target, err := confiner.Resolve(p.GetPath(), fsutil.TargetEntry) + if err != nil { + return fileOpErrResp(rid, err) + } + defer target.Close() + + if err := target.Root.Chmod(target.Rel, permMode(p.GetMode())); err != nil { + return fileOpErrResp(rid, err) + } + return fileOpOkResp(rid) +} + +func (h *GRPCFileHandler) handleChownOp( + confiner *fsutil.Confiner, rid string, p *pb.ChownParams, +) (*pb.FileOperationResponse, error) { + if p == nil { + return fileOpErrResp(rid, errors.New("chown_params required")) + } + target, err := confiner.Resolve(p.GetPath(), fsutil.TargetEntry) + if err != nil { + return fileOpErrResp(rid, err) + } + defer target.Close() + + if err := target.Root.Chown(target.Rel, int(p.GetUid()), int(p.GetGid())); err != nil { return fileOpErrResp(rid, err) } return fileOpOkResp(rid) } func (h *GRPCFileHandler) handleMkdirOp( - root *os.Root, rid string, p *pb.MkdirParams, + confiner *fsutil.Confiner, rid string, p *pb.MkdirParams, ) (*pb.FileOperationResponse, error) { if p == nil { return fileOpErrResp(rid, errors.New("mkdir_params required")) } - rel, err := fsutil.RootRel(p.GetPath()) + target, err := confiner.Resolve(p.GetPath(), fsutil.TargetEntry) if err != nil { return fileOpErrResp(rid, err) } + defer target.Close() + + root, rel := target.Root, target.Rel owner := osowner.Options{ User: p.GetOwnerUser(), @@ -560,15 +602,19 @@ func (h *GRPCFileHandler) handleMkdirOp( } func (h *GRPCFileHandler) handleTouchOp( - root *os.Root, rid string, p *pb.TouchParams, + confiner *fsutil.Confiner, rid string, p *pb.TouchParams, ) (*pb.FileOperationResponse, error) { if p == nil { return fileOpErrResp(rid, errors.New("touch_params required")) } - rel, err := fsutil.RootRel(p.GetPath()) + target, err := confiner.Resolve(p.GetPath(), fsutil.TargetEntry) if err != nil { return fileOpErrResp(rid, err) } + defer target.Close() + + root, rel := target.Root, target.Rel + if _, statErr := root.Stat(rel); os.IsNotExist(statErr) { f, createErr := root.Create(rel) if createErr != nil { @@ -587,7 +633,7 @@ func (h *GRPCFileHandler) handleTouchOp( } func (h *GRPCFileHandler) handleHashOp( - ctx context.Context, root *os.Root, rid string, p *pb.HashParams, + ctx context.Context, confiner *fsutil.Confiner, rid string, p *pb.HashParams, ) (*pb.FileOperationResponse, error) { if p == nil { return fileOpErrResp(rid, errors.New("hash_params required")) @@ -607,7 +653,7 @@ func (h *GRPCFileHandler) handleHashOp( return fileOpErrResp(rid, errors.Wrap(err, "hash operation canceled")) } - hashes = append(hashes, hashFileInRoot(ctx, root, pth, p.GetAlgorithm())) + hashes = append(hashes, hashConfinedFile(ctx, confiner, pth, p.GetAlgorithm())) } return &pb.FileOperationResponse{ @@ -622,18 +668,27 @@ func (h *GRPCFileHandler) handleHashOp( }, nil } -// hashFileInRoot hashes a single file inside root. Any failure is reported in -// the returned FileHash.Error; per-file failures must not fail the operation. -func hashFileInRoot( - ctx context.Context, root *os.Root, path string, algorithm pb.HashAlgorithm, +// hashConfinedFile hashes a single file. Every path is placed on its own: the +// paths of one request need not share a game server directory. Any failure is +// reported in the returned FileHash.Error; per-file failures must not fail the +// operation. +func hashConfinedFile( + ctx context.Context, confiner *fsutil.Confiner, path string, algorithm pb.HashAlgorithm, ) *pb.FileHash { - fh := &pb.FileHash{Path: path} - - rel, err := fsutil.RootRel(path) + target, err := confiner.Resolve(path, fsutil.TargetEntry) if err != nil { - fh.Error = err.Error() - return fh + return &pb.FileHash{Path: path, Error: err.Error()} } + defer target.Close() + + return hashFileInRoot(ctx, target.Root, target.Rel, path, algorithm) +} + +// hashFileInRoot hashes the file rel of root and reports it under requestPath. +func hashFileInRoot( + ctx context.Context, root *os.Root, rel, requestPath string, algorithm pb.HashAlgorithm, +) *pb.FileHash { + fh := &pb.FileHash{Path: requestPath} info, err := root.Lstat(rel) if err != nil { diff --git a/internal/app/grpc/transfer_confinement_unix_test.go b/internal/app/grpc/transfer_confinement_unix_test.go new file mode 100644 index 0000000..23090d3 --- /dev/null +++ b/internal/app/grpc/transfer_confinement_unix_test.go @@ -0,0 +1,281 @@ +//go:build linux || darwin + +package grpc + +import ( + "context" + "os" + "path/filepath" + "testing" + + pb "github.com/gameap/gameap/pkg/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" +) + +// fakeTransferService stands in for the panel side of FileTransferService: it +// serves one payload to download and records what is uploaded to it. +type fakeTransferService struct { + pb.FileTransferServiceClient + + payload []byte + uploaded []byte + uploads int +} + +func (f *fakeTransferService) DownloadFile( + _ context.Context, _ *pb.DownloadRequest, _ ...grpc.CallOption, +) (grpc.ServerStreamingClient[pb.DownloadChunk], error) { + return &fakeDownloadStream{ + fakeChunkReceiver: &fakeChunkReceiver{ + chunks: []*pb.DownloadChunk{{Data: f.payload, IsFinal: true, ChecksumSha256: sha256Hex(f.payload)}}, + }, + }, nil +} + +func (f *fakeTransferService) UploadFile( + _ context.Context, _ ...grpc.CallOption, +) (grpc.ClientStreamingClient[pb.UploadChunk, pb.UploadResult], error) { + f.uploads++ + + return &fakeUploadStream{service: f}, nil +} + +type fakeDownloadStream struct { + grpc.ClientStream + *fakeChunkReceiver +} + +type fakeUploadStream struct { + grpc.ClientStream + + service *fakeTransferService +} + +func (s *fakeUploadStream) Send(chunk *pb.UploadChunk) error { + s.service.uploaded = append(s.service.uploaded, chunk.GetData()...) + + return nil +} + +func (s *fakeUploadStream) CloseAndRecv() (*pb.UploadResult, error) { + return &pb.UploadResult{Success: true}, nil +} + +func transferResponse(t *testing.T, sender *fakeSender) *pb.FileWriteResponse { + t.Helper() + + sender.mu.Lock() + defer sender.mu.Unlock() + + require.Len(t, sender.msgs, 1) + + resp := sender.msgs[0].GetFileWriteResponse() + require.NotNil(t, resp) + + return resp +} + +func TestGRPCTransferHandler_UploadTask_Confinement(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + path string + wantError string + // wantFile is where the payload must land, relative to the work directory. + wantFile string + }{ + { + name: "own_file", + path: "servers/a/addons/new/uploaded.txt", + wantFile: "servers/a/addons/new/uploaded.txt", + }, + { + name: "own_file_behind_a_link_staying_inside", + path: "servers/a/in-link/uploaded.cfg", + wantFile: "servers/a/cstrike/uploaded.cfg", + }, + { + name: "into_the_neighbour_through_a_link", + path: "servers/a/servers-link/b/planted.txt", + wantError: "path escapes from parent", + }, + { + name: "over_a_node_file_through_a_link", + path: "servers/a/node-link/steamcmd/steamcmd.sh", + wantError: "path escapes from parent", + }, + { + // The finished upload is renamed into place, which replaces the + // link itself: the file it pointed at is left alone. + name: "link_to_a_neighbour_file_is_replaced_not_followed", + path: "servers/a/file-link", + wantFile: "servers/a/file-link", + }, + } + + for modeName, mode := range confinementModes() { + for _, tt := range tests { + t.Run(modeName+"/"+tt.name, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + outside := []string{"servers/b", "steamcmd", ".plugins"} + + before := map[string]map[string]string{} + for _, dir := range outside { + before[dir] = snapshotTree(t, filepath.Join(workDir, filepath.FromSlash(dir))) + } + + sender := &fakeSender{} + service := &fakeTransferService{payload: []byte("uploaded payload")} + h := NewGRPCTransferHandler(workDir, &FileTransferClient{client: service}, sender, 1, mode.opts...) + + h.HandleFileUploadTask(context.Background(), "req", &pb.FileUploadTask{ + TransferId: "tid", + Path: tt.path, + Root: mode.root, + }) + + resp := transferResponse(t, sender) + + for _, dir := range outside { + assert.Equal(t, before[dir], snapshotTree(t, filepath.Join(workDir, filepath.FromSlash(dir))), dir) + } + + if tt.wantError != "" { + assert.False(t, resp.GetSuccess()) + assert.Contains(t, resp.GetError(), tt.wantError) + + return + } + + require.True(t, resp.GetSuccess(), resp.GetError()) + + info, err := os.Lstat(filepath.Join(workDir, filepath.FromSlash(tt.wantFile))) + require.NoError(t, err) + assert.True(t, info.Mode().IsRegular(), info.Mode().String()) + + content, err := os.ReadFile(filepath.Join(workDir, filepath.FromSlash(tt.wantFile))) + require.NoError(t, err) + assert.Equal(t, "uploaded payload", string(content)) + + _, err = os.Lstat(filepath.Join(workDir, filepath.FromSlash(tt.wantFile)+".tmp_tid")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + } + } +} + +func TestGRPCTransferHandler_DownloadTask_Confinement(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + path string + wantError string + wantUpload string + }{ + { + name: "own_file", + path: "servers/a/cstrike/server.cfg", + wantUpload: "hostname a", + }, + { + name: "own_file_behind_a_link_staying_inside", + path: "servers/a/in-link/server.cfg", + wantUpload: "hostname a", + }, + { + name: "neighbour_config_through_a_link", + path: "servers/a/servers-link/b/cstrike/server.cfg", + wantError: "path escapes from parent", + }, + { + name: "neighbour_config_through_a_file_link", + path: "servers/a/file-link", + wantError: "path escapes from parent", + }, + { + name: "plugin_secret_through_a_link", + path: "servers/a/users-link/srv.yaml", + wantError: "path escapes from parent", + }, + } + + for modeName, mode := range confinementModes() { + for _, tt := range tests { + t.Run(modeName+"/"+tt.name, func(t *testing.T) { + t.Parallel() + + sender := &fakeSender{} + service := &fakeTransferService{} + h := NewGRPCTransferHandler( + tenantWorkDir(t), &FileTransferClient{client: service}, sender, 1, mode.opts..., + ) + + h.HandleFileDownloadTask(context.Background(), "req", &pb.FileDownloadTask{ + TransferId: "tid", + Path: tt.path, + Root: mode.root, + }) + + resp := transferResponse(t, sender) + + if tt.wantError != "" { + assert.False(t, resp.GetSuccess()) + assert.Contains(t, resp.GetError(), tt.wantError) + assert.Zero(t, service.uploads) + assert.Empty(t, service.uploaded) + + return + } + + require.True(t, resp.GetSuccess(), resp.GetError()) + assert.Equal(t, tt.wantUpload, string(service.uploaded)) + }) + } + } +} + +func TestGRPCTransferHandler_PathOutsideTheRequestRoot(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + service := &fakeTransferService{payload: []byte("x")} + + t.Run("upload_task", func(t *testing.T) { + t.Parallel() + + sender := &fakeSender{} + h := NewGRPCTransferHandler(workDir, &FileTransferClient{client: service}, sender, 1) + + h.HandleFileUploadTask(context.Background(), "req", &pb.FileUploadTask{ + TransferId: "up", Path: "servers/b/planted.txt", Root: "servers/a", + }) + + resp := transferResponse(t, sender) + assert.False(t, resp.GetSuccess()) + assert.Equal(t, "path is outside its confinement root", resp.GetError()) + + _, err := os.Lstat(filepath.Join(workDir, "servers", "b", "planted.txt")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) + + t.Run("download_task", func(t *testing.T) { + t.Parallel() + + sender := &fakeSender{} + h := NewGRPCTransferHandler(workDir, &FileTransferClient{client: service}, sender, 1) + + h.HandleFileDownloadTask(context.Background(), "req", &pb.FileDownloadTask{ + TransferId: "down", Path: "servers/b/cstrike/server.cfg", Root: "servers/a", + }) + + resp := transferResponse(t, sender) + assert.False(t, resp.GetSuccess()) + assert.Equal(t, "path is outside its confinement root", resp.GetError()) + }) +} diff --git a/internal/app/grpc/transfer_handler.go b/internal/app/grpc/transfer_handler.go index f3c721b..c2b4df1 100644 --- a/internal/app/grpc/transfer_handler.go +++ b/internal/app/grpc/transfer_handler.go @@ -24,6 +24,7 @@ const ( type GRPCTransferHandler struct { workDir string + confineOpts []fsutil.ConfineOption fileTransfer *FileTransferClient responseSender ResponseSender sem *semaphore.Weighted @@ -35,6 +36,7 @@ func NewGRPCTransferHandler( fileTransfer *FileTransferClient, responseSender ResponseSender, maxConcurrent int64, + confineOpts ...fsutil.ConfineOption, ) *GRPCTransferHandler { if maxConcurrent <= 0 { maxConcurrent = defaultMaxConcurrentTransfers @@ -42,23 +44,16 @@ func NewGRPCTransferHandler( return &GRPCTransferHandler{ workDir: workDir, + confineOpts: confineOpts, fileTransfer: fileTransfer, responseSender: responseSender, sem: semaphore.NewWeighted(maxConcurrent), } } -// openRoot opens an os.Root at the work directory so every caller-supplied -// path is resolved component-by-component without symlink/".." escapes or -// TOCTOU races. Opened per request because workDir is provisioned from the -// API after construction. -func (h *GRPCTransferHandler) openRoot() (*os.Root, error) { - root, err := os.OpenRoot(h.workDir) - if err != nil { - return nil, errors.Wrap(err, "work directory unavailable") - } - - return root, nil +// confiner returns the path resolver of one transfer, see GRPCFileHandler.confiner. +func (h *GRPCTransferHandler) confiner(root string) *fsutil.Confiner { + return requestConfiner(h.workDir, h.confineOpts, root) } // HandleFileUploadTask handles a file upload task from the API. @@ -72,20 +67,15 @@ func (h *GRPCTransferHandler) HandleFileUploadTask(ctx context.Context, requestI l.Info("Handling file upload task (download from API)") - root, err := h.openRoot() - if err != nil { - l.WithError(err).Error("Failed to open work directory") - h.sendResponse(requestID, false, err.Error()) - return - } - defer root.Close() - - rel, err := fsutil.RootRel(task.Path) + target, err := h.confiner(task.GetRoot()).Resolve(task.Path, fsutil.TargetEntry) if err != nil { l.WithError(err).Error("Failed to resolve path") h.sendResponse(requestID, false, err.Error()) return } + defer target.Close() + + root, rel := target.Root, target.Rel tempRel := rel + ".tmp_" + task.TransferId @@ -265,20 +255,15 @@ func (h *GRPCTransferHandler) HandleFileDownloadTask(ctx context.Context, reques l.Info("Handling file download task (upload to API)") - root, err := h.openRoot() - if err != nil { - l.WithError(err).Error("Failed to open work directory") - h.sendResponse(requestID, false, err.Error()) - return - } - defer root.Close() - - rel, err := fsutil.RootRel(task.Path) + target, err := h.confiner(task.GetRoot()).Resolve(task.Path, fsutil.TargetEntry) if err != nil { l.WithError(err).Error("Failed to resolve path") h.sendResponse(requestID, false, err.Error()) return } + defer target.Close() + + root, rel := target.Root, target.Rel info, err := root.Stat(rel) if err != nil { diff --git a/internal/app/repositories/server_repository.go b/internal/app/repositories/server_repository.go index 4d366a1..24e9450 100644 --- a/internal/app/repositories/server_repository.go +++ b/internal/app/repositories/server_repository.go @@ -28,6 +28,21 @@ func (repo *ServerRepository) IDsFromCache() []int { return ids } +// ServerDirs returns the directory of every cached server, relative to the +// work directory. File requests are confined by them, see fsutil.Confiner. +func (repo *ServerRepository) ServerDirs() []string { + var dirs []string + repo.servers.Range(func(_, value interface{}) bool { + if server, ok := value.(*domain.Server); ok { + dirs = append(dirs, server.Dir()) + } + + return true + }) + + return dirs +} + func (repo *ServerRepository) IDs(_ context.Context) ([]int, error) { return repo.IDsFromCache(), nil } diff --git a/internal/app/repositories/server_repository_test.go b/internal/app/repositories/server_repository_test.go new file mode 100644 index 0000000..dde0fd9 --- /dev/null +++ b/internal/app/repositories/server_repository_test.go @@ -0,0 +1,54 @@ +package repositories + +import ( + "testing" + "time" + + "github.com/gameap/daemon/internal/app/domain" + "github.com/stretchr/testify/assert" +) + +func serverWithDir(id int, dir string) *domain.Server { + return domain.NewServer( + id, + true, + domain.ServerInstalled, + false, + "test", + "uuid", + "uuid", + domain.Game{}, + domain.GameMod{}, + "127.0.0.1", + 27015, 27016, 27020, + "", + dir, + "gameap", + "start", "stop", "kill", "restart", + false, + time.Now(), + nil, + nil, + time.Now(), + 0, 0, + ) +} + +func TestServerRepository_ServerDirs(t *testing.T) { + t.Parallel() + + repo := NewServerRepository() + + assert.Empty(t, repo.ServerDirs()) + + repo.SaveToCache(serverWithDir(1, "servers/a")) + repo.SaveToCache(serverWithDir(2, "servers/b")) + + assert.ElementsMatch(t, []string{"servers/a", "servers/b"}, repo.ServerDirs()) + + // A config push for a server already cached replaces its directory: the old + // one stops being a boundary together with the server leaving it. + repo.SaveToCache(serverWithDir(2, "servers/moved")) + + assert.ElementsMatch(t, []string{"servers/a", "servers/moved"}, repo.ServerDirs()) +} From 8681c90cc318be95974ed9525a4edad25b347714 Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 17 Nov 2026 19:06:22 +0100 Subject: [PATCH 2/7] review and ci fails fixes --- go.mod | 8 +- go.sum | 12 +- internal/app/archive/archiver.go | 8 + internal/app/archive/confine_unix_test.go | 220 ++++++++++++++++++ internal/app/archive/create.go | 192 ++++++++++++--- internal/app/archive/create_single.go | 4 +- internal/app/archive/create_tar.go | 4 +- internal/app/archive/create_test.go | 17 +- internal/app/archive/create_zip.go | 4 +- internal/app/fsutil/confine.go | 214 +++++++++++++---- internal/app/fsutil/confine_test.go | 56 +++++ internal/app/fsutil/confine_unix_test.go | 154 ++++++++++++ internal/app/fsutil/copy.go | 138 ++++++++--- internal/app/fsutil/copy_test.go | 153 ++++++++++++ internal/app/fsutil/copy_unix_test.go | 37 +++ internal/app/fsutil/rename_test.go | 12 + .../install_server_test.go | 10 +- .../app/grpc/file_confinement_unix_test.go | 92 ++++++++ .../grpc/transfer_confinement_unix_test.go | 55 ++++- internal/app/grpc/transfer_handler.go | 8 +- .../serverscommand/install/install_test.go | 10 +- 21 files changed, 1256 insertions(+), 152 deletions(-) diff --git a/go.mod b/go.mod index e55944c..d9b5ee6 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/gameap/daemon -go 1.27.2 +go 1.27.4 require ( github.com/bodgit/sevenzip v1.6.5 @@ -8,12 +8,12 @@ require ( github.com/dgraph-io/ristretto/v2 v2.4.2 github.com/dsnet/compress v0.0.1 github.com/emirpasic/gods v1.18.1 - github.com/gameap/gameap v0.0.0-20260902160210-6f8f727046bf + github.com/gameap/gameap v0.0.0-20261117172108-d6ea2698d6dc github.com/gameap/gameapctl v0.34.0 github.com/goccy/go-yaml v1.19.2 github.com/gopherclass/go-shellquote v0.0.0-20200814145606-fab22d094485 github.com/hashicorp/go-getter v1.8.9 - github.com/klauspost/compress v1.20.0 + github.com/klauspost/compress v1.20.2 github.com/moby/moby/api v1.56.0 github.com/moby/moby/client v0.6.0 github.com/nwaples/rardecode/v2 v2.4.1 @@ -44,7 +44,7 @@ require ( github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.57.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect - github.com/andybalholm/brotli v1.2.2 // indirect + github.com/andybalholm/brotli v1.2.7 // indirect github.com/aws/aws-sdk-go-v2 v1.44.0 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect github.com/aws/aws-sdk-go-v2/config v1.32.40 // indirect diff --git a/go.sum b/go.sum index e3b79de..c4b86f5 100644 --- a/go.sum +++ b/go.sum @@ -30,8 +30,8 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapp github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.57.0/go.mod h1:YqwkQPrWSC7+byyc1VlKbWLBF5JsW5IoL6xUkemYSXk= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= -github.com/andybalholm/brotli v1.2.2 h1:HzTuoo2ErYQqf5qvcJInB8uvqSVxRttzkFexPWtnceM= -github.com/andybalholm/brotli v1.2.2/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= +github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/aws/aws-sdk-go-v2 v1.44.0 h1:4IbaHhtzy+4h37z4JQyO9a2QsiCml3CNYHtq5hIHigo= github.com/aws/aws-sdk-go-v2 v1.44.0/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs= @@ -117,8 +117,8 @@ github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMD github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= -github.com/gameap/gameap v0.0.0-20260902160210-6f8f727046bf h1:eTYQRWvJAb7HXbh8NxHu3S1cu2TbfD6cmeMYjpdb7MA= -github.com/gameap/gameap v0.0.0-20260902160210-6f8f727046bf/go.mod h1:N1sXbvSi3/FQcnJeXXRh89GEGbZzUxds+3cFz65BkG8= +github.com/gameap/gameap v0.0.0-20261117172108-d6ea2698d6dc h1:LMVh7qTvigb0Q/Fqj7Pd9SFIl3A2E6MUCuq3Ctr2J4A= +github.com/gameap/gameap v0.0.0-20261117172108-d6ea2698d6dc/go.mod h1:RAzSBEIOhFOQNuifdmpZmPyTArWvZacSmHHOsZd4Km0= github.com/gameap/gameapctl v0.34.0 h1:OJvAFEkONLk1Uhzj2vv2cZLuwXJwL3fqOySy3jIKUGI= github.com/gameap/gameapctl v0.34.0/go.mod h1:GEUPbmHDrnFYxVUqN3FpE7afnrEQkjtdrlK96ENeHkE= github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= @@ -160,8 +160,8 @@ github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09 github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA= -github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo= +github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= diff --git a/internal/app/archive/archiver.go b/internal/app/archive/archiver.go index 59400dc..6d043a3 100644 --- a/internal/app/archive/archiver.go +++ b/internal/app/archive/archiver.go @@ -9,6 +9,14 @@ // lexically when their path is absolute or starts with ".." (zip-slip), // because the API contract requires the friendly error. // +// A request acting for the node may start above the game server directories. +// Create holds to the same boundary there: every source is placed on its own, +// and a game server directory entered while a larger tree is packed is read +// through a root opened at it. Extract does not: an archive unpacked above the +// game server directories is written through the root of its destination +// alone, so an entry naming a path inside one of them is followed through the +// links standing there, as far as the destination reaches. +// // Extraction feeds attacker-controlled bytes to third-party format decoders, // so the caller is expected to run it under a recover (see the gRPC archive // handler). One residual risk cannot be handled here: bodgit/sevenzip sizes diff --git a/internal/app/archive/confine_unix_test.go b/internal/app/archive/confine_unix_test.go index ac3bdee..655ff4f 100644 --- a/internal/app/archive/confine_unix_test.go +++ b/internal/app/archive/confine_unix_test.go @@ -5,6 +5,7 @@ package archive import ( "archive/zip" "context" + "io" "os" "path/filepath" "testing" @@ -72,6 +73,34 @@ func zipEntryNames(t *testing.T, path string) []string { return names } +// zipContents reads the body of every regular entry of a zip archive. +func zipContents(t *testing.T, path string) map[string]string { + t.Helper() + + r, err := zip.OpenReader(path) + require.NoError(t, err) + defer r.Close() + + contents := map[string]string{} + + for _, f := range r.File { + if !f.Mode().IsRegular() { + continue + } + + rc, err := f.Open() + require.NoError(t, err) + + body, err := io.ReadAll(rc) + require.NoError(t, err) + require.NoError(t, rc.Close()) + + contents[f.Name] = string(body) + } + + return contents +} + func TestCreate_Confinement(t *testing.T) { t.Parallel() @@ -473,3 +502,194 @@ func TestArchive_NodeLevelAcrossServerDirs(t *testing.T) { assert.Equal(t, "#!/bin/sh", string(content)) }) } + +// A caller acting for the node may start above the game server directories: +// pack one of them from the work directory, or all of them at once. The tree +// it reads still belongs to the tenants, so each game server directory it +// enters confines what is read below it, as if the request had started there. +func TestCreate_SourcesAboveTheServerDirs(t *testing.T) { + t.Parallel() + + opts := []fsutil.ConfineOption{fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})} + + refused := []struct { + name string + params *pb.CreateArchiveParams + }{ + { + name: "server_named_as_a_source", + params: &pb.CreateArchiveParams{ + BasePath: ".", Sources: []string{"servers/a"}, FollowSymlinks: true, + }, + }, + { + name: "link_of_a_server_named_as_a_source", + params: &pb.CreateArchiveParams{ + BasePath: ".", Sources: []string{"servers/a/file-link"}, FollowSymlinks: true, + }, + }, + { + name: "source_named_through_a_link_of_a_server", + params: &pb.CreateArchiveParams{ + BasePath: ".", Sources: []string{"servers/a/servers-link/b/cstrike/server.cfg"}, + }, + }, + { + name: "directory_holding_the_servers", + params: &pb.CreateArchiveParams{ + BasePath: ".", Sources: []string{"servers"}, FollowSymlinks: true, + }, + }, + { + name: "whole_work_directory", + params: &pb.CreateArchiveParams{ + BasePath: "", Sources: []string{"."}, FollowSymlinks: true, + }, + }, + { + name: "base_path_holding_the_servers", + params: &pb.CreateArchiveParams{ + BasePath: "servers", Sources: []string{"a", "b"}, FollowSymlinks: true, + }, + }, + } + + for _, tt := range refused { + t.Run("refused/"+tt.name, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + neighbour := readTree(t, filepath.Join(workDir, "servers", "b")) + + tt.params.ArchivePath = "backups/node.zip" + + res, err := Create(context.Background(), workDir, tt.params, nil, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, res) + assert.Equal(t, neighbour, readTree(t, filepath.Join(workDir, "servers", "b"))) + + _, statErr := os.Lstat(filepath.Join(workDir, "backups", "node.zip")) + assert.ErrorIs(t, statErr, os.ErrNotExist, "a refused operation leaves no archive behind") + }) + } + + t.Run("links_are_packed_as_links", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: ".", + Sources: []string{"servers"}, + }, nil, opts...) + + require.NoError(t, err) + assert.ElementsMatch(t, []string{ + "servers/", + "servers/a/", "servers/a/own.txt", "servers/a/cstrike/", "servers/a/cstrike/server.cfg", + "servers/a/servers-link", "servers/a/node-link", "servers/a/file-link", "servers/a/in-link", + "servers/b/", "servers/b/victim.txt", "servers/b/cstrike/", "servers/b/cstrike/server.cfg", + }, zipEntryNames(t, filepath.Join(workDir, "backups", "node.zip"))) + }) + + t.Run("links_staying_inside_their_server_are_followed", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + for _, link := range []string{"servers-link", "node-link", "file-link"} { + require.NoError(t, os.Remove(filepath.Join(workDir, "servers", "a", link))) + } + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: ".", + Sources: []string{"servers", "steamcmd"}, + FollowSymlinks: true, + }, nil, opts...) + + require.NoError(t, err) + + archive := filepath.Join(workDir, "backups", "node.zip") + + assert.ElementsMatch(t, []string{ + "servers/", + "servers/a/", "servers/a/own.txt", "servers/a/cstrike/", "servers/a/cstrike/server.cfg", + "servers/a/in-link/", "servers/a/in-link/server.cfg", + "servers/b/", "servers/b/victim.txt", "servers/b/cstrike/", "servers/b/cstrike/server.cfg", + "steamcmd/", "steamcmd/steamcmd.sh", + }, zipEntryNames(t, archive)) + + contents := zipContents(t, archive) + assert.Equal(t, "hostname a", contents["servers/a/in-link/server.cfg"]) + assert.Equal(t, "rcon_password secret", contents["servers/b/cstrike/server.cfg"]) + assert.Equal(t, "#!/bin/sh", contents["steamcmd/steamcmd.sh"]) + }) + + // A node-level link standing outside every game server directory leads + // into one: what is read through it is read as that server's tree. + t.Run("server_reached_through_a_node_link_is_confined", func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + writeTree(t, workDir, map[string]string{"shortcuts/.keep": ""}) + require.NoError(t, os.Symlink("../servers/a", filepath.Join(workDir, "shortcuts", "current"))) + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: ".", + Sources: []string{"shortcuts"}, + FollowSymlinks: true, + }, nil, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) +} + +// Many sources, and many links to one game server directory, are read through +// the roots already open: the walk must not hold a descriptor for each. +func TestSourceWalker_SharesRoots(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + for _, link := range []string{"servers-link", "node-link", "file-link"} { + require.NoError(t, os.Remove(filepath.Join(workDir, "servers", "a", link))) + } + + writeTree(t, workDir, map[string]string{"shortcuts/.keep": ""}) + for _, name := range []string{"one", "two", "three"} { + require.NoError(t, os.Symlink("../servers/a", filepath.Join(workDir, "shortcuts", name))) + } + + confiner := fsutil.NewConfiner(workDir, fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})) + + base, err := confiner.Resolve(".", fsutil.TargetTree) + require.NoError(t, err) + defer base.Close() + + w := &sourceWalker{ + ctx: context.Background(), + confiner: confiner, + limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, + } + defer w.close() + + entries, err := w.collect(base, ".", []string{ + "servers/a/own.txt", "servers/a/cstrike", "servers/a", "shortcuts", "steamcmd", "servers/b/victim.txt", + }) + require.NoError(t, err) + require.NotEmpty(t, entries) + + assert.Len(t, w.scopes, 3, "the work directory and the two game server directories") + + for _, e := range entries { + content, readErr := e.root.ReadFile(e.rel) + if e.info.Mode().IsRegular() { + require.NoError(t, readErr, e.name) + assert.NotNil(t, content) + } + } +} diff --git a/internal/app/archive/create.go b/internal/app/archive/create.go index 68766e9..83ab0fa 100644 --- a/internal/app/archive/create.go +++ b/internal/app/archive/create.go @@ -17,8 +17,9 @@ import ( // sourceEntry is one item scheduled for archiving: a regular file, a // directory or a symlink stored as-is. type sourceEntry struct { - rel string // path inside the root - name string // entry name inside the archive, relative to base_path + root *os.Root // the root the entry is read through + rel string // path inside the root + name string // entry name inside the archive, relative to base_path info os.FileInfo link string // symlink target, set when the symlink is stored as a symlink } @@ -99,7 +100,7 @@ func Create( acc := newAccumulator(p.GetMaxTotalBytes(), p.GetMaxFiles(), progress) - createErr := createInto(ctx, base.Root, archiveFile, base.Rel, p, format, class, acc) + createErr := createInto(ctx, confiner, base, archiveFile, p, format, class, acc) closeErr := archiveFile.Close() if createErr != nil { @@ -148,9 +149,9 @@ func Create( func createInto( ctx context.Context, - root *os.Root, + confiner *fsutil.Confiner, + base *fsutil.Confined, archiveFile *os.File, - baseRel string, p *pb.CreateArchiveParams, format pb.ArchiveFormat, class formatClass, @@ -161,17 +162,24 @@ func createInto( return errors.Wrap(err, "failed to stat archive file") } - entries, err := collectSources(ctx, root, baseRel, p.GetSources(), &walkLimits{ - follow: p.GetFollowSymlinks(), - maxEntries: acc.maxFiles, - archive: archiveInfo, - }) + walker := &sourceWalker{ + ctx: ctx, + confiner: confiner, + limits: &walkLimits{ + follow: p.GetFollowSymlinks(), + maxEntries: acc.maxFiles, + archive: archiveInfo, + }, + } + defer walker.close() + + entries, err := walker.collect(base, p.GetBasePath(), p.GetSources()) if err != nil { return err } if class == classSingle { - return createSingle(root, archiveFile, entries, p, format, acc) + return createSingle(archiveFile, entries, p, format, acc) } if len(entries) == 0 { @@ -179,10 +187,10 @@ func createInto( } if class == classZip { - return createZip(ctx, root, archiveFile, entries, p, acc) + return createZip(ctx, archiveFile, entries, p, acc) } - return createTar(ctx, root, archiveFile, entries, p, tarCompression(format), acc) + return createTar(ctx, archiveFile, entries, p, tarCompression(format), acc) } // walkLimits bounds one source expansion. @@ -202,19 +210,49 @@ type walkLimits struct { // sourceWalker expands the request sources (relative to base_path) into a flat // entry list. Directories are walked recursively; symlinks are stored as // symlinks unless follow is set, in which case the symlink target contents are -// archived (os.Root still refuses targets outside the work directory). +// archived. +// +// Every source is placed by the confiner on its own, and a game server +// directory the walk enters from above is read through a root opened at it. +// A tree packed for the node is thus confined the way a tree packed for one +// game server is: os.Root refuses a link leading out of the game server +// directory it stands in, whichever directory the request started from. type sourceWalker struct { - ctx context.Context - root *os.Root - limits *walkLimits - entries []sourceEntry + ctx context.Context + confiner *fsutil.Confiner + limits *walkLimits + entries []sourceEntry + scopes []sourceScope +} + +// sourceScope is a root the sources are read through. +type sourceScope struct { + root *os.Root + dir os.FileInfo + // owned roots are opened by the walker and closed with it. + owned bool +} + +// close releases the roots the entries are read through, so it has to wait +// until the archive is written. +func (w *sourceWalker) close() { + for _, scope := range w.scopes { + if scope.owned { + _ = scope.root.Close() + } + } } -// collectSources expands every source into one flat, bounded entry list. -func collectSources( - ctx context.Context, root *os.Root, baseRel string, sources []string, limits *walkLimits, -) ([]sourceEntry, error) { - w := &sourceWalker{ctx: ctx, root: root, limits: limits} +// collect expands every source into one flat, bounded entry list. +func (w *sourceWalker) collect(base *fsutil.Confined, basePath string, sources []string) ([]sourceEntry, error) { + baseRel, err := fsutil.RootRel(basePath) + if err != nil { + return nil, err + } + + if _, err := w.adopt(base.Root, false); err != nil { + return nil, err + } for _, src := range sources { srcRel, err := fsutil.RootRel(src) @@ -222,12 +260,17 @@ func collectSources( return nil, errors.Wrapf(err, "invalid source %q", src) } - rel := srcRel - if baseRel != "." { - rel = path.Join(baseRel, srcRel) + placed, err := w.confiner.Resolve(path.Join(baseRel, srcRel), fsutil.TargetTree) + if err != nil { + return nil, err } - if err := w.walk(rel, srcRel, 0); err != nil { + root, err := w.adopt(placed.Root, true) + if err != nil { + return nil, err + } + + if err := w.walk(root, placed.Rel, srcRel, 0); err != nil { return nil, err } } @@ -235,6 +278,43 @@ func collectSources( return w.entries, nil } +// adopt returns the root to read the directory of root through: the one +// already open there, or root itself, which is then kept. The sources of one +// request mostly share a directory, and a link can lead to a game server +// directory any number of times; neither may cost a descriptor each. +func (w *sourceWalker) adopt(root *os.Root, owned bool) (*os.Root, error) { + dir, err := root.Stat(".") + if err != nil { + if owned { + _ = root.Close() + } + + return nil, errors.Wrap(err, "failed to stat source directory") + } + + if known := w.scopeOf(dir); known != nil { + if owned { + _ = root.Close() + } + + return known, nil + } + + w.scopes = append(w.scopes, sourceScope{root: root, dir: dir, owned: owned}) + + return root, nil +} + +func (w *sourceWalker) scopeOf(dir os.FileInfo) *os.Root { + for _, scope := range w.scopes { + if os.SameFile(scope.dir, dir) { + return scope.root + } + } + + return nil +} + func (w *sourceWalker) add(e sourceEntry) error { if uint64(len(w.entries)) >= w.limits.maxEntries { return errors.Errorf("max files limit exceeded (%d)", w.limits.maxEntries) @@ -263,12 +343,12 @@ func copySource(root *os.Root, rel string, w io.Writer, bytesLeft int64) (int64, return n, nil } -func (w *sourceWalker) walk(rel, name string, symlinkDepth int) error { +func (w *sourceWalker) walk(root *os.Root, rel, name string, symlinkDepth int) error { if err := w.ctx.Err(); err != nil { return errors.Wrap(err, "create archive canceled") } - info, err := w.root.Lstat(rel) + info, err := root.Lstat(rel) if err != nil { return errors.Wrapf(err, "failed to stat source %q", rel) } @@ -283,7 +363,7 @@ func (w *sourceWalker) walk(rel, name string, symlinkDepth int) error { return errors.Errorf("symlink nesting too deep at %q", rel) } - info, err = w.root.Stat(rel) + info, err = root.Stat(rel) if err != nil { return errors.Wrapf(err, "failed to resolve symlink %q", rel) } @@ -297,16 +377,16 @@ func (w *sourceWalker) walk(rel, name string, symlinkDepth int) error { switch { case info.IsDir(): - return w.walkDir(rel, name, info, symlinkDepth) + return w.walkDir(root, rel, name, info, symlinkDepth) case info.Mode()&os.ModeSymlink != 0: - link, err := w.root.Readlink(rel) + link, err := root.Readlink(rel) if err != nil { return errors.Wrapf(err, "failed to read symlink %q", rel) } - return w.add(sourceEntry{rel: rel, name: name, info: info, link: link}) + return w.add(sourceEntry{root: root, rel: rel, name: name, info: info, link: link}) case info.Mode().IsRegular(): - return w.add(sourceEntry{rel: rel, name: name, info: info}) + return w.add(sourceEntry{root: root, rel: rel, name: name, info: info}) default: // Sockets, fifos and device nodes cannot be archived; game-server work // directories legitimately contain unix sockets. Matches fsutil.Copy. @@ -314,16 +394,21 @@ func (w *sourceWalker) walk(rel, name string, symlinkDepth int) error { } } -func (w *sourceWalker) walkDir(rel, name string, info os.FileInfo, symlinkDepth int) error { +func (w *sourceWalker) walkDir(root *os.Root, rel, name string, info os.FileInfo, symlinkDepth int) error { + root, rel, err := w.enter(root, rel, info) + if err != nil { + return err + } + // The "." source contributes its children only; storing "." itself would // produce a useless root entry. if name != "." { - if err := w.add(sourceEntry{rel: rel, name: name, info: info}); err != nil { + if err := w.add(sourceEntry{root: root, rel: rel, name: name, info: info}); err != nil { return err } } - dirEntries, err := fs.ReadDir(w.root.FS(), rel) + dirEntries, err := fs.ReadDir(root.FS(), rel) if err != nil { return errors.Wrapf(err, "failed to read directory %q", rel) } @@ -334,10 +419,41 @@ func (w *sourceWalker) walkDir(rel, name string, info os.FileInfo, symlinkDepth childName = path.Join(name, child.Name()) } - if err := w.walk(path.Join(rel, child.Name()), childName, symlinkDepth); err != nil { + if err := w.walk(root, path.Join(rel, child.Name()), childName, symlinkDepth); err != nil { return err } } return nil } + +// enter returns where to read the directory rel of root from. A game server +// directory is read through a root of its own from there on; any other +// directory stays where it is. +func (w *sourceWalker) enter(root *os.Root, rel string, info os.FileInfo) (*os.Root, string, error) { + if rel == "." || !w.confiner.IsServerDir(info) { + return root, rel, nil + } + + if known := w.scopeOf(info); known != nil { + // A link back to the directory the walk is already confined to keeps + // its path, and with it the limit os.Root puts on a chain of links. + if known == root { + return root, rel, nil + } + + return known, ".", nil + } + + inner, err := root.OpenRoot(rel) + if err != nil { + return nil, "", errors.Wrapf(err, "failed to open game server directory %q", rel) + } + + inner, err = w.adopt(inner, true) + if err != nil { + return nil, "", err + } + + return inner, ".", nil +} diff --git a/internal/app/archive/create_single.go b/internal/app/archive/create_single.go index 61ac557..bfdffa6 100644 --- a/internal/app/archive/create_single.go +++ b/internal/app/archive/create_single.go @@ -2,7 +2,6 @@ package archive import ( "io" - "os" "github.com/pkg/errors" @@ -12,7 +11,6 @@ import ( // createSingle writes the gz/bz2/xz/zstd single-file formats: the archive is // the compressed stream of exactly one regular file. func createSingle( - root *os.Root, archiveFile io.Writer, entries []sourceEntry, p *pb.CreateArchiveParams, @@ -39,7 +37,7 @@ func createSingle( } }() - n, err := copySource(root, e.rel, stream, acc.bytesLeft()) + n, err := copySource(e.root, e.rel, stream, acc.bytesLeft()) if err != nil { return err } diff --git a/internal/app/archive/create_tar.go b/internal/app/archive/create_tar.go index 889b6bd..4d2f509 100644 --- a/internal/app/archive/create_tar.go +++ b/internal/app/archive/create_tar.go @@ -6,7 +6,6 @@ import ( "compress/gzip" "context" "io" - "os" "strings" "github.com/pkg/errors" @@ -98,7 +97,6 @@ func decompressReader(r io.Reader, comp compression) (io.ReadCloser, error) { // compressor (tar.gz, tar.bz2, tar.xz, tar.zst). func createTar( ctx context.Context, - root *os.Root, w io.Writer, entries []sourceEntry, p *pb.CreateArchiveParams, @@ -140,7 +138,7 @@ func createTar( var n int64 if hdr.Typeflag == tar.TypeReg { - n, err = copySource(root, e.rel, tw, acc.bytesLeft()) + n, err = copySource(e.root, e.rel, tw, acc.bytesLeft()) if err != nil { return err } diff --git a/internal/app/archive/create_test.go b/internal/app/archive/create_test.go index f4e3ab2..52dc52d 100644 --- a/internal/app/archive/create_test.go +++ b/internal/app/archive/create_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/gameap/daemon/internal/app/fsutil" pb "github.com/gameap/gameap/pkg/proto" ) @@ -553,12 +554,12 @@ func TestWalkSourceSymlinkDepthLimit(t *testing.T) { defer root.Close() w := &sourceWalker{ - ctx: context.Background(), - root: root, - limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, + ctx: context.Background(), + confiner: fsutil.NewConfiner(workDir), + limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, } - err = w.walk("src/loop", "src/loop", maxFollowDepth) + err = w.walk(root, "src/loop", "src/loop", maxFollowDepth) require.Error(t, err) assert.Contains(t, err.Error(), "symlink nesting too deep") } @@ -615,12 +616,12 @@ func TestSourceWalkerRespectsContext(t *testing.T) { defer root.Close() w := &sourceWalker{ - ctx: canceledContext(t), - root: root, - limits: &walkLimits{maxEntries: defaultMaxFilesLimit()}, + ctx: canceledContext(t), + confiner: fsutil.NewConfiner(workDir), + limits: &walkLimits{maxEntries: defaultMaxFilesLimit()}, } - err = w.walk("src", "src", 0) + err = w.walk(root, "src", "src", 0) require.ErrorIs(t, err, context.Canceled) } diff --git a/internal/app/archive/create_zip.go b/internal/app/archive/create_zip.go index bd37e87..cbeb5bc 100644 --- a/internal/app/archive/create_zip.go +++ b/internal/app/archive/create_zip.go @@ -5,7 +5,6 @@ import ( "compress/flate" "context" "io" - "os" "github.com/pkg/errors" @@ -16,7 +15,6 @@ import ( // per-entry Store; other levels tune the deflate compressor. func createZip( ctx context.Context, - root *os.Root, w io.Writer, entries []sourceEntry, p *pb.CreateArchiveParams, @@ -71,7 +69,7 @@ func createZip( return errors.Wrapf(writeErr, "failed to write symlink %q", e.name) } default: - n, err = copySource(root, e.rel, entryWriter, acc.bytesLeft()) + n, err = copySource(e.root, e.rel, entryWriter, acc.bytesLeft()) if err != nil { return err } diff --git a/internal/app/fsutil/confine.go b/internal/app/fsutil/confine.go index 67c19f1..457a870 100644 --- a/internal/app/fsutil/confine.go +++ b/internal/app/fsutil/confine.go @@ -2,9 +2,9 @@ package fsutil import ( "os" - "runtime" "slices" "strings" + "sync" "github.com/pkg/errors" ) @@ -82,10 +82,24 @@ func WithRoot(root string) ConfineOption { // opened fd-relative like any other component: an absolute or escaping symlink // in its own path is refused, including one the tenant of an outer game server // puts in place of a directory nested in its own. +// +// A boundary is a directory, not a name. A path may spell a game server +// directory or the request root unlike the daemon does: in another letter case +// on a case-insensitive volume, by a Windows short name, through a link +// standing next to it. Such a path is placed by the directory it leads to. +// +// Resolve places the path a request names, and nothing below it. An operation +// that walks a tree from above the game server directories, as a request +// acting for the node rather than for one server can, crosses into them +// through the root it started with unless it asks IsServerDir about the +// directories it enters. type Confiner struct { workDir string serverDirs ServerDirLister root string + + identify sync.Once + identities []os.FileInfo } // NewConfiner creates a Confiner anchored at workDir. @@ -114,9 +128,57 @@ func (c *Confined) Close() error { } // SameRoot reports whether both paths live in one root, so that a single-root -// primitive such as os.Root.Rename can take them together. +// primitive such as os.Root.Rename can take them together. The roots are +// compared as directories: Scope is spelled the way each request path spells +// it, and two spellings can name one directory or two. func (c *Confined) SameRoot(other *Confined) bool { - return sameDir(c.Scope, other.Scope) + own, err := c.Root.Stat(".") + if err != nil { + return false + } + + theirs, err := other.Root.Stat(".") + if err != nil { + return false + } + + return os.SameFile(own, theirs) +} + +// IsServerDir reports whether info describes a game server directory. A walk +// that starts above the game server directories uses it to notice the ones it +// enters, which no request path names. +func (c *Confiner) IsServerDir(info os.FileInfo) bool { + if c.serverDirs == nil || !info.IsDir() { + return false + } + + c.identify.Do(func() { + root, err := os.OpenRoot(c.workDir) + if err != nil { + return + } + defer root.Close() + + for _, serverDir := range c.serverDirs.ServerDirs() { + dir, err := RootRel(serverDir) + if err != nil || dir == "." { + continue + } + + if known, err := root.Stat(dir); err == nil && known.IsDir() { + c.identities = append(c.identities, known) + } + } + }) + + for _, known := range c.identities { + if os.SameFile(info, known) { + return true + } + } + + return false } // Resolve places a caller-supplied path. See Confiner for the model. @@ -172,36 +234,23 @@ func (c *Confiner) boundaries(rel string, target Target) ([]string, error) { return nil, err } - switch { - case root == ".": - // The work directory already confines every path. - case sameDir(rel, root): - lengths = append(lengths, len(rel)) - case isBelow(rel, root): - lengths = append(lengths, len(root)) - default: - return nil, ErrPathOutsideConfinement + // The work directory already confines every path. + if root != "." { + n := leadingLen(rel, root) + if n == 0 || !c.sameDir(rel[:n], root) { + return nil, ErrPathOutsideConfinement + } + + lengths = append(lengths, n) } } if c.serverDirs != nil { - for _, serverDir := range c.serverDirs.ServerDirs() { - dir, err := RootRel(serverDir) - if err != nil || dir == "." { - continue - } - - switch { - case isBelow(rel, dir): - lengths = append(lengths, len(dir)) - case target == TargetTree && sameDir(rel, dir): - lengths = append(lengths, len(rel)) - } - } + lengths = c.serverBoundaries(rel, target, lengths) } - // Every match is a prefix of rel, so ordering by length puts an enclosing - // directory before the one nested in it. + // Every match is a leading part of rel, so ordering by length puts an + // enclosing directory before the one nested in it. slices.Sort(lengths) lengths = slices.Compact(lengths) @@ -213,17 +262,108 @@ func (c *Confiner) boundaries(rel string, target Target) ([]string, error) { return dirs, nil } -// isBelow reports whether rel names something strictly inside dir. -func isBelow(rel, dir string) bool { - if dir == "." { - return rel != "." +// serverBoundaries adds the leading parts of rel that are game server +// directories to lengths. +func (c *Confiner) serverBoundaries(rel string, target Target, lengths []int) []int { + // Leading parts as deep as a game server directory but spelled unlike it. + var loose []int + + for _, serverDir := range c.serverDirs.ServerDirs() { + dir, err := RootRel(serverDir) + if err != nil || dir == "." { + continue + } + + n := leadingLen(rel, dir) + // An entry named as such belongs to the directory holding it. + if n == 0 || (n == len(rel) && target != TargetTree) { + continue + } + + if rel[:n] == dir { + lengths = append(lengths, n) + } else { + loose = append(loose, n) + } + } + + slices.Sort(loose) + + // The usual request spells its game server directory the way the daemon + // knows it and is settled above without touching the disk. What is left + // may still be one under another spelling, which only the disk can tell. + for _, n := range slices.Compact(loose) { + if slices.Contains(lengths, n) { + continue + } + + if info, err := c.stat(rel[:n]); err == nil && c.IsServerDir(info) { + lengths = append(lengths, n) + } + } + + return lengths +} + +// leadingLen returns the length of the leading part of rel that is as deep as +// dir, or 0 when rel is not that deep. +func leadingLen(rel, dir string) int { + if rel == "." { + return 0 + } + + end := 0 + + for range strings.Count(dir, "/") + 1 { + if end == len(rel) { + return 0 + } + + if end > 0 { + end++ + } + + next := strings.IndexByte(rel[end:], '/') + if next < 0 { + end = len(rel) + } else { + end += next + } + } + + return end +} + +// sameDir reports whether two names lead to one directory of the work +// directory. Names spelled alike do without a lookup, which also covers a +// directory that is not on disk yet. +func (c *Confiner) sameDir(a, b string) bool { + if a == b { + return true } - if len(rel) <= len(dir) || rel[len(dir)] != '/' { + infoA, err := c.stat(a) + if err != nil || !infoA.IsDir() { return false } - return sameDir(rel[:len(dir)], dir) + infoB, err := c.stat(b) + if err != nil { + return false + } + + return os.SameFile(infoA, infoB) +} + +// stat describes what a name relative to the work directory leads to. +func (c *Confiner) stat(name string) (os.FileInfo, error) { + root, err := os.OpenRoot(c.workDir) + if err != nil { + return nil, err + } + defer root.Close() + + return root.Stat(name) } // relativeTo expresses rel, which is base or lies below it, relative to base. @@ -238,11 +378,3 @@ func relativeTo(rel, base string) string { return rel[len(base)+1:] } - -func sameDir(a, b string) bool { - if runtime.GOOS == "windows" { - return strings.EqualFold(a, b) - } - - return a == b -} diff --git a/internal/app/fsutil/confine_test.go b/internal/app/fsutil/confine_test.go index 395b569..9110968 100644 --- a/internal/app/fsutil/confine_test.go +++ b/internal/app/fsutil/confine_test.go @@ -379,3 +379,59 @@ func TestConfined_SameRoot(t *testing.T) { assert.False(t, own.SameRoot(node)) assert.True(t, node.SameRoot(resolve("servers/a"))) } + +func TestConfiner_IsServerDir(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + + stat := func(name string) os.FileInfo { + info, err := os.Stat(filepath.Join(workDir, filepath.FromSlash(name))) + require.NoError(t, err) + + return info + } + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{ + "servers/a", "/servers/b/", "servers/absent", "servers/a/own.txt", ".", "../outside", + })) + + assert.True(t, confiner.IsServerDir(stat("servers/a"))) + assert.True(t, confiner.IsServerDir(stat("servers/b"))) + assert.False(t, confiner.IsServerDir(stat("servers/ab"))) + assert.False(t, confiner.IsServerDir(stat("servers"))) + assert.False(t, confiner.IsServerDir(stat("servers/a/sub"))) + assert.False(t, confiner.IsServerDir(stat("servers/a/own.txt")), "a file is no directory to confine to") + assert.False(t, confiner.IsServerDir(stat(".")), "the work directory is not a boundary of its own") + + assert.False(t, NewConfiner(workDir).IsServerDir(stat("servers/a"))) + assert.False(t, NewConfiner(workDir, WithRoot("servers/a")).IsServerDir(stat("servers/a"))) +} + +func TestLeadingLen(t *testing.T) { + t.Parallel() + + tests := []struct { + rel string + dir string + want string + }{ + {rel: "servers/a/sub/inner.txt", dir: "servers/a", want: "servers/a"}, + {rel: "servers/a", dir: "servers/a", want: "servers/a"}, + {rel: "servers/ab/other.txt", dir: "servers/a", want: "servers/ab"}, + {rel: "SERVERS/A/own.txt", dir: "servers/a", want: "SERVERS/A"}, + {rel: "servers/a/own.txt", dir: "servers", want: "servers"}, + {rel: "servers/a/nested/deep.md", dir: "servers/a/nested", want: "servers/a/nested"}, + {rel: "servers", dir: "servers/a", want: ""}, + {rel: "servers/a", dir: "servers/a/nested", want: ""}, + {rel: ".", dir: "servers", want: ""}, + } + + for _, tt := range tests { + t.Run(tt.rel+"_"+tt.dir, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, tt.rel[:leadingLen(tt.rel, tt.dir)]) + }) + } +} diff --git a/internal/app/fsutil/confine_unix_test.go b/internal/app/fsutil/confine_unix_test.go index f9952ea..d35c8e6 100644 --- a/internal/app/fsutil/confine_unix_test.go +++ b/internal/app/fsutil/confine_unix_test.go @@ -284,3 +284,157 @@ func TestConfiner_RequestRootKeepsTheServerDirBoundary(t *testing.T) { }) } } + +// A game server directory reached under a name the daemon does not know it by +// is still that directory: the request is confined to it all the same. +func TestConfiner_ServerDirUnderAnotherName(t *testing.T) { + t.Parallel() + + newTree := func(t *testing.T) string { + t.Helper() + + workDir := confineTree(t) + plantLinks(t, workDir) + require.NoError(t, os.Symlink("a", filepath.Join(workDir, "servers", "alias"))) + + return workDir + } + + known := WithServerDirs(serverDirs{"servers/a", "servers/b"}) + + t.Run("path_below_it_is_confined", func(t *testing.T) { + t.Parallel() + + got, err := NewConfiner(newTree(t), known).Resolve("servers/alias/servers-link/b/secret.cfg", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/alias", got.Scope) + assert.Equal(t, "servers-link/b/secret.cfg", got.Rel) + + _, err = got.Root.ReadFile(got.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) + + t.Run("own_file_stays_reachable", func(t *testing.T) { + t.Parallel() + + got, err := NewConfiner(newTree(t), known).Resolve("servers/alias/sub/inner.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + content, err := got.Root.ReadFile(got.Rel) + require.NoError(t, err) + assert.Equal(t, "inner", string(content)) + }) + + t.Run("the_directory_itself_follows_the_target", func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + entry, err := confiner.Resolve("servers/alias", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = entry.Close() }) + assert.Equal(t, ".", entry.Scope) + + tree, err := confiner.Resolve("servers/alias", TargetTree) + require.NoError(t, err) + t.Cleanup(func() { _ = tree.Close() }) + assert.Equal(t, "servers/alias", tree.Scope) + assert.Equal(t, ".", tree.Rel) + }) + + t.Run("it_is_inside_the_request_root_it_names", func(t *testing.T) { + t.Parallel() + + got, err := NewConfiner(newTree(t), WithRoot("servers/a")).Resolve("servers/alias/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/alias", got.Scope) + + _, err = got.Root.Stat("servers-link/b/secret.cfg") + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) + + t.Run("another_directory_stays_outside_the_request_root", func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + require.NoError(t, os.Symlink("b", filepath.Join(workDir, "servers", "other"))) + + got, err := NewConfiner(workDir, WithRoot("servers/a")).Resolve("servers/other/secret.cfg", TargetEntry) + + require.ErrorIs(t, err, ErrPathOutsideConfinement) + assert.Nil(t, got) + }) + + t.Run("both_names_share_one_root", func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + byName, err := confiner.Resolve("servers/a/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = byName.Close() }) + + byAlias, err := confiner.Resolve("servers/alias/sub/inner.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = byAlias.Close() }) + + assert.True(t, byName.SameRoot(byAlias)) + }) +} + +// Whether "Servers/a" is the directory "servers/a" depends on the volume, so +// the daemon asks the disk rather than compare the names: both answers have to +// come out right. The test takes whichever volume it runs on. +func TestConfiner_ServerDirSpelledInAnotherCase(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + + known := WithServerDirs(serverDirs{"servers/a", "servers/b"}) + + lower, err := os.Stat(filepath.Join(workDir, "servers")) + require.NoError(t, err) + + if upper, statErr := os.Stat(filepath.Join(workDir, "SERVERS")); statErr == nil && os.SameFile(lower, upper) { + got, err := NewConfiner(workDir, known).Resolve("SERVERS/A/servers-link/b/secret.cfg", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "SERVERS/A", got.Scope) + + _, err = got.Root.ReadFile(got.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + + rooted, err := NewConfiner(workDir, WithRoot("servers/a")).Resolve("Servers/A/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = rooted.Close() }) + + assert.Equal(t, "Servers/A", rooted.Scope) + assert.True(t, got.SameRoot(rooted)) + + return + } + + require.NoError(t, os.MkdirAll(filepath.Join(workDir, "SERVERS", "A"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(workDir, "SERVERS", "A", "own.txt"), []byte("another"), 0o644)) + + got, err := NewConfiner(workDir, known).Resolve("SERVERS/A/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, ".", got.Scope, "a directory of its own is not the game server directory") + + rooted, err := NewConfiner(workDir, WithRoot("servers/a")).Resolve("SERVERS/A/own.txt", TargetEntry) + + require.ErrorIs(t, err, ErrPathOutsideConfinement) + assert.Nil(t, rooted) +} diff --git a/internal/app/fsutil/copy.go b/internal/app/fsutil/copy.go index 2380b0c..7fea564 100644 --- a/internal/app/fsutil/copy.go +++ b/internal/app/fsutil/copy.go @@ -31,6 +31,15 @@ type CopyOptions struct { AddPermission os.FileMode } +// ErrCopyIntoItself is returned when the destination of a directory copy is +// the source directory or lies inside it. Such a copy never ends on its own: +// it keeps finding, and copying, what it has just written. +var ErrCopyIntoItself = errors.New("cannot copy a directory into itself") + +// ErrCopySameFile is returned when the source and the destination of a copy +// are one file. Opening the destination for writing would empty the source. +var ErrCopySameFile = errors.New("source and destination are the same file") + // CopyInRoot copies src to dst where both are paths relative to the same root. func CopyInRoot(root *os.Root, src, dst string, opts CopyOptions) error { return CopyTree(root, src, root, dst, opts) @@ -39,13 +48,59 @@ func CopyInRoot(root *os.Root, src, dst string, opts CopyOptions) error { // CopyTree copies srcRoot:src into dstRoot:dst. Directories are merged into an // existing destination and regular files overwrite an existing one, matching // the default behaviour of the recursive-copy library this package replaced. +// +// A destination that is the source, or lies inside it, is refused with +// ErrCopyIntoItself or ErrCopySameFile. func CopyTree(srcRoot *os.Root, src string, dstRoot *os.Root, dst string, opts CopyOptions) error { info, err := srcRoot.Lstat(src) if err != nil { return errors.Wrap(err, "failed to stat copy source") } - return copyEntry(srcRoot, src, dstRoot, dst, info, opts) + if err := refuseOverlap(info, dstRoot, dst); err != nil { + return errors.WithMessagef(err, "failed to copy %q to %q", src, dst) + } + + _, dstErr := dstRoot.Lstat(dst) + + c := &copier{srcRoot: srcRoot, dstRoot: dstRoot, opts: opts} + + err = c.entry(src, dst, info) + // A refused copy leaves nothing behind, as long as all of it is its own. + if errors.Is(err, ErrCopyIntoItself) && errors.Is(dstErr, os.ErrNotExist) { + _ = dstRoot.RemoveAll(dst) + } + + return err +} + +// refuseOverlap rejects, before anything is written, a copy whose destination +// is the source or one of the directories the destination is created in. The +// two are compared as files, not by name: they are named through different +// roots, and one directory can be spelled in more than one way. +// +// A destination whose path leads into the source from outside of dstRoot, or +// through a link, is not seen from here; copier.dir stops that copy as soon as +// it reaches the destination. +func refuseOverlap(src fs.FileInfo, dstRoot *os.Root, dst string) error { + switch { + case src.IsDir(): + for dir := dst; ; dir = path.Dir(dir) { + if info, err := dstRoot.Stat(dir); err == nil && os.SameFile(src, info) { + return ErrCopyIntoItself + } + + if dir == "." || dir == "/" { + return nil + } + } + case src.Mode().IsRegular(): + if info, err := dstRoot.Stat(dst); err == nil && os.SameFile(src, info) { + return ErrCopySameFile + } + } + + return nil } // Copy copies absolute src to absolute dst. It is a convenience for trusted, @@ -99,18 +154,25 @@ func Copy(src, dst string, opts CopyOptions) error { return CopyTree(srcRoot, filepath.Base(src), dstRoot, filepath.Base(dst), opts) } -func copyEntry( - srcRoot *os.Root, src string, dstRoot *os.Root, dst string, info fs.FileInfo, opts CopyOptions, -) error { +// copier carries one CopyTree call through the source tree. +type copier struct { + srcRoot *os.Root + dstRoot *os.Root + opts CopyOptions + // dstTop is the directory the copy writes into, known once it is created. + dstTop fs.FileInfo +} + +func (c *copier) entry(src, dst string, info fs.FileInfo) error { mode := info.Mode() switch { case mode&os.ModeSymlink != 0: - return copySymlink(srcRoot, src, dstRoot, dst, opts) + return c.symlink(src, dst) case mode.IsDir(): - return copyDir(srcRoot, src, dstRoot, dst, info, opts) + return c.dir(src, dst, info) case mode.IsRegular(): - return copyFile(srcRoot, src, dstRoot, dst, info, opts) + return c.file(src, dst, info) default: // Sockets, fifos and device nodes are skipped: a running game server // keeps unix sockets in its work directory and copying them is both @@ -119,14 +181,28 @@ func copyEntry( } } -func copyDir( - srcRoot *os.Root, src string, dstRoot *os.Root, dst string, info fs.FileInfo, opts CopyOptions, -) error { - if err := ensureDir(dstRoot, dst, dirPerm(info)); err != nil { +func (c *copier) dir(src, dst string, info fs.FileInfo) error { + // The destination turned up inside the source. Descending into it would + // copy the copy, one level deeper each time, until the disk or the stack + // gives out. + if c.dstTop != nil && os.SameFile(info, c.dstTop) { + return errors.WithMessagef(ErrCopyIntoItself, "source directory %q is the destination", src) + } + + if err := ensureDir(c.dstRoot, dst, dirPerm(info)); err != nil { return err } - entries, err := fs.ReadDir(srcRoot.FS(), src) + if c.dstTop == nil { + top, err := c.dstRoot.Stat(dst) + if err != nil { + return errors.Wrap(err, "failed to stat destination directory") + } + + c.dstTop = top + } + + entries, err := fs.ReadDir(c.srcRoot.FS(), src) if err != nil { return errors.Wrap(err, "failed to read source directory") } @@ -135,12 +211,12 @@ func copyDir( childSrc := path.Join(src, entry.Name()) childDst := path.Join(dst, entry.Name()) - childInfo, err := srcRoot.Lstat(childSrc) + childInfo, err := c.srcRoot.Lstat(childSrc) if err != nil { return errors.Wrap(err, "failed to stat directory entry") } - if err := copyEntry(srcRoot, childSrc, dstRoot, childDst, childInfo, opts); err != nil { + if err := c.entry(childSrc, childDst, childInfo); err != nil { return err } } @@ -148,22 +224,20 @@ func copyDir( return nil } -func copyFile( - srcRoot *os.Root, src string, dstRoot *os.Root, dst string, info fs.FileInfo, opts CopyOptions, -) error { - if err := ensureParent(dstRoot, dst); err != nil { +func (c *copier) file(src, dst string, info fs.FileInfo) error { + if err := ensureParent(c.dstRoot, dst); err != nil { return err } - srcFile, err := srcRoot.Open(src) + srcFile, err := c.srcRoot.Open(src) if err != nil { return errors.Wrap(err, "failed to open source file") } defer srcFile.Close() - perm := (info.Mode() | opts.AddPermission).Perm() + perm := (info.Mode() | c.opts.AddPermission).Perm() - dstFile, err := dstRoot.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) + dstFile, err := c.dstRoot.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) if err != nil { return errors.Wrap(err, "failed to create destination file") } @@ -179,46 +253,44 @@ func copyFile( // Restore the exact source mode: OpenFile is subject to umask, which would // otherwise strip the executable bit from game-server scripts. - if err := dstRoot.Chmod(dst, perm); err != nil { + if err := c.dstRoot.Chmod(dst, perm); err != nil { return errors.Wrap(err, "failed to set destination file mode") } return nil } -func copySymlink( - srcRoot *os.Root, src string, dstRoot *os.Root, dst string, opts CopyOptions, -) error { - switch opts.Symlink { +func (c *copier) symlink(src, dst string) error { + switch c.opts.Symlink { case SymlinkSkip: return nil case SymlinkDeep: - target, err := srcRoot.Stat(src) + target, err := c.srcRoot.Stat(src) if err != nil { return errors.Wrap(err, "failed to stat symlink target") } switch { case target.IsDir(): - return copyDir(srcRoot, src, dstRoot, dst, target, opts) + return c.dir(src, dst, target) case target.Mode().IsRegular(): - return copyFile(srcRoot, src, dstRoot, dst, target, opts) + return c.file(src, dst, target) default: return nil } default: // SymlinkShallow - linkTarget, err := srcRoot.Readlink(src) + linkTarget, err := c.srcRoot.Readlink(src) if err != nil { return errors.Wrap(err, "failed to read symlink") } - if err := ensureParent(dstRoot, dst); err != nil { + if err := ensureParent(c.dstRoot, dst); err != nil { return err } - _ = dstRoot.Remove(dst) + _ = c.dstRoot.Remove(dst) - if err := dstRoot.Symlink(linkTarget, dst); err != nil { + if err := c.dstRoot.Symlink(linkTarget, dst); err != nil { return errors.Wrap(err, "failed to create symlink") } diff --git a/internal/app/fsutil/copy_test.go b/internal/app/fsutil/copy_test.go index a14b5f6..bf5cca9 100644 --- a/internal/app/fsutil/copy_test.go +++ b/internal/app/fsutil/copy_test.go @@ -103,3 +103,156 @@ func TestCopyInRoot_SameRoot(t *testing.T) { require.NoError(t, err) assert.Equal(t, "z", string(got)) } + +func openTestRoot(t *testing.T, dir string) *os.Root { + t.Helper() + + root, err := os.OpenRoot(dir) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + return root +} + +func TestCopyTree_DirectoryIntoItself(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + // srcRoot and dstRoot are relative to the work directory. + srcRoot string + src string + dstRoot string + dst string + // created is what a copy would have made, relative to the work directory. + created string + }{ + {name: "onto_itself", srcRoot: ".", src: "servers/a", dstRoot: ".", dst: "servers/a"}, + {name: "into_a_new_child", srcRoot: ".", src: "servers/a", dstRoot: ".", dst: "servers/a/clone", created: "servers/a/clone"}, + {name: "into_an_existing_child", srcRoot: ".", src: "servers/a", dstRoot: ".", dst: "servers/a/sub"}, + { + name: "into_a_new_descendant", + srcRoot: ".", src: "servers", dstRoot: ".", dst: "servers/a/backups/today/clone", + created: "servers/a/backups", + }, + {name: "root_into_its_own_child", srcRoot: "servers/a", src: ".", dstRoot: "servers/a", dst: "clone", created: "servers/a/clone"}, + { + name: "destination_named_through_a_root_inside_the_source", + srcRoot: ".", src: "servers", dstRoot: "servers/a", dst: "clone", + created: "servers/a/clone", + }, + { + name: "destination_is_a_root_inside_the_source", + srcRoot: ".", src: "servers", dstRoot: "servers/a", dst: ".", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + before := treeFiles(t, workDir) + + srcRoot := openTestRoot(t, filepath.Join(workDir, filepath.FromSlash(tt.srcRoot))) + dstRoot := openTestRoot(t, filepath.Join(workDir, filepath.FromSlash(tt.dstRoot))) + + err := CopyTree(srcRoot, tt.src, dstRoot, tt.dst, CopyOptions{}) + + require.ErrorIs(t, err, ErrCopyIntoItself) + assert.Equal(t, before, treeFiles(t, workDir), "a refused copy changes no file") + + if tt.created != "" { + _, statErr := os.Lstat(filepath.Join(workDir, filepath.FromSlash(tt.created))) + assert.ErrorIs(t, statErr, os.ErrNotExist, "a refused copy leaves no destination behind") + } + }) + } +} + +func TestCopyTree_NextToTheSourceIsNotIntoIt(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + src string + dst string + want string + }{ + {name: "sibling", src: "servers/a", dst: "servers/clone", want: "servers/clone/sub/inner.txt"}, + {name: "name_sharing_a_prefix", src: "servers/a", dst: "servers/a-clone", want: "servers/a-clone/sub/inner.txt"}, + {name: "into_another_server", src: "servers/a", dst: "servers/b/from-a", want: "servers/b/from-a/sub/inner.txt"}, + {name: "child_into_its_parent", src: "servers/a/sub", dst: "servers/a", want: "servers/a/inner.txt"}, + {name: "child_next_to_itself", src: "servers/a/sub", dst: "servers/a/sub2", want: "servers/a/sub2/inner.txt"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + root := openTestRoot(t, workDir) + + require.NoError(t, CopyTree(root, tt.src, root, tt.dst, CopyOptions{})) + + content, err := os.ReadFile(filepath.Join(workDir, filepath.FromSlash(tt.want))) + require.NoError(t, err) + assert.Equal(t, "inner", string(content)) + }) + } +} + +func TestCopyTree_FileOntoItself(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + root := openTestRoot(t, workDir) + serverRoot := openTestRoot(t, filepath.Join(workDir, "servers", "a")) + + err := CopyTree(root, "servers/a/own.txt", root, "servers/a/own.txt", CopyOptions{}) + require.ErrorIs(t, err, ErrCopySameFile) + + err = CopyTree(root, "servers/a/own.txt", serverRoot, "own.txt", CopyOptions{}) + require.ErrorIs(t, err, ErrCopySameFile) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "a", "own.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content), "the source must not be emptied") + + require.NoError(t, CopyTree(root, "servers/a/own.txt", root, "servers/a/own-copy.txt", CopyOptions{})) +} + +// treeFiles reads every regular file below dir, keyed by its slash-separated +// path, and lists the directories, so that two snapshots compare as a whole. +func treeFiles(t *testing.T, dir string) map[string]string { + t.Helper() + + files := map[string]string{} + + require.NoError(t, filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { + if err != nil { + return err + } + + rel, err := filepath.Rel(dir, p) + if err != nil { + return err + } + + switch { + case d.IsDir(): + files[filepath.ToSlash(rel)+"/"] = "" + case d.Type().IsRegular(): + content, err := os.ReadFile(p) + if err != nil { + return err + } + + files[filepath.ToSlash(rel)] = string(content) + } + + return nil + })) + + return files +} diff --git a/internal/app/fsutil/copy_unix_test.go b/internal/app/fsutil/copy_unix_test.go index f24a888..7a35826 100644 --- a/internal/app/fsutil/copy_unix_test.go +++ b/internal/app/fsutil/copy_unix_test.go @@ -70,3 +70,40 @@ func TestCopy_SkipsNonRegularFiles(t *testing.T) { _, err = os.Lstat(filepath.Join(dst, "pipe")) assert.ErrorIs(t, err, os.ErrNotExist, "the fifo must be skipped, not copied") } + +// The destination reaches into the source through a link, so no directory the +// destination is named by is the source. The copy is stopped where it finds +// its own destination, and what it made until then is removed. +func TestCopyTree_DirectoryIntoItselfThroughALink(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("servers/a/nested", filepath.Join(workDir, "shortcut"))) + + before := treeFiles(t, workDir) + root := openTestRoot(t, workDir) + + err := CopyTree(root, "servers", root, "shortcut/clone", CopyOptions{}) + + require.ErrorIs(t, err, ErrCopyIntoItself) + assert.Equal(t, before, treeFiles(t, workDir)) + + _, statErr := os.Lstat(filepath.Join(workDir, "servers", "a", "nested", "clone")) + assert.ErrorIs(t, statErr, os.ErrNotExist) +} + +func TestCopyTree_FileOntoItselfThroughALink(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("own.txt", filepath.Join(workDir, "servers", "a", "own-link.txt"))) + + root := openTestRoot(t, workDir) + + err := CopyTree(root, "servers/a/own.txt", root, "servers/a/own-link.txt", CopyOptions{}) + require.ErrorIs(t, err, ErrCopySameFile) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "a", "own.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) +} diff --git a/internal/app/fsutil/rename_test.go b/internal/app/fsutil/rename_test.go index 4fc840d..af81508 100644 --- a/internal/app/fsutil/rename_test.go +++ b/internal/app/fsutil/rename_test.go @@ -206,6 +206,18 @@ func TestMoveByCopy(t *testing.T) { assert.Equal(t, "own", string(content)) }) + t.Run("directory_into_itself", func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + before := treeFiles(t, workDir) + + err := moveByCopy(openTestRoot(t, workDir), "servers", openTestRoot(t, filepath.Join(workDir, "servers", "a")), "moved") + + require.ErrorIs(t, err, ErrCopyIntoItself) + assert.Equal(t, before, treeFiles(t, workDir), "neither the source nor a half-made destination is touched") + }) + t.Run("missing_source_leaves_no_destination", func(t *testing.T) { t.Parallel() diff --git a/internal/app/game_server_commands/install_server_test.go b/internal/app/game_server_commands/install_server_test.go index 8165f3a..232aacb 100644 --- a/internal/app/game_server_commands/install_server_test.go +++ b/internal/app/game_server_commands/install_server_test.go @@ -526,12 +526,12 @@ func givenRemoteInstallationServer(t *testing.T) *domain.Server { game := domain.Game{ StartCode: "test", - RemoteRepository: "https://files.gameap.ru/test/test.tar.xz", + RemoteRepository: "https://cdn.gameap.com/test/test.tar.xz", } gameMod := domain.GameMod{ Name: "test", - RemoteRepository: "https://files.gameap.ru/mod-game.tar.gz", + RemoteRepository: "https://cdn.gameap.com/mod-game.tar.gz", } return givenServer(t, game, gameMod) @@ -569,13 +569,13 @@ func givenLocalInstallationGame(t *testing.T) (domain.Game, domain.GameMod) { game := domain.Game{ StartCode: "test", LocalRepository: pathToFileZip, - RemoteRepository: "https://files.gameap.ru/test/test.tar.xz", + RemoteRepository: "https://cdn.gameap.com/test/test.tar.xz", } gameMod := domain.GameMod{ Name: "test", LocalRepository: pathToDirectory, - RemoteRepository: "https://files.gameap.ru/mod-game.tar.gz", + RemoteRepository: "https://cdn.gameap.com/mod-game.tar.gz", } return game, gameMod @@ -592,7 +592,7 @@ func givenLocalInstallationServerWithAfterInstallScript(t *testing.T) *domain.Se game := domain.Game{ StartCode: "test", LocalRepository: pathToFileZip, - RemoteRepository: "https://files.gameap.ru/test/test.tar.xz", + RemoteRepository: "https://cdn.gameap.com/test/test.tar.xz", } gameMod := domain.GameMod{ diff --git a/internal/app/grpc/file_confinement_unix_test.go b/internal/app/grpc/file_confinement_unix_test.go index 69ceaa6..1177dfb 100644 --- a/internal/app/grpc/file_confinement_unix_test.go +++ b/internal/app/grpc/file_confinement_unix_test.go @@ -791,6 +791,26 @@ func TestGRPCFileHandler_NodeLevelOperationsAcrossServerDirs(t *testing.T) { assert.Equal(t, "../..", target) }) + t.Run("copy_the_servers_into_one_of_them_is_refused", func(t *testing.T) { + t.Parallel() + + h, workDir := newHandler(t) + before := snapshotTree(t, workDir) + + // The source is read through the work directory and the destination + // written through the directory of server "a": the two paths share no + // root, and still the copy would end up copying itself. + resp := fileOp(t, h, "", pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{Source: "servers", Destination: "servers/a/clone"}, + } + }) + + assert.False(t, resp.GetSuccess()) + assert.Contains(t, resp.GetError(), "cannot copy a directory into itself") + assert.Equal(t, before, snapshotTree(t, workDir)) + }) + t.Run("copy_into_a_server_does_not_follow_a_planted_link", func(t *testing.T) { t.Parallel() @@ -856,3 +876,75 @@ func TestGRPCFileHandler_NodeLevelOperationsAcrossServerDirs(t *testing.T) { } }) } + +// A directory copied into itself would be copied again with every level the +// copy adds. The request is refused before anything is written. +func TestGRPCFileHandler_CopyIntoItselfIsRefused(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + source string + destination string + wantError string + }{ + { + name: "directory_into_its_child", + source: "servers/a/cstrike", + destination: "servers/a/cstrike/backup", + wantError: "cannot copy a directory into itself", + }, + { + name: "directory_into_its_descendant", + source: "servers/a/cstrike", + destination: "servers/a/cstrike/maps/old/backup", + wantError: "cannot copy a directory into itself", + }, + { + name: "directory_into_its_child_named_through_a_link", + source: "servers/a/cstrike", + destination: "servers/a/in-link/backup", + wantError: "cannot copy a directory into itself", + }, + { + name: "whole_server_dir_into_its_child", + source: "servers/a", + destination: "servers/a/backup", + wantError: "cannot copy a directory into itself", + }, + { + name: "directory_onto_itself", + source: "servers/a/cstrike", + destination: "servers/a/cstrike", + wantError: "cannot copy a directory into itself", + }, + { + name: "file_onto_itself", + source: "servers/a/own.txt", + destination: "servers/a/own.txt", + wantError: "source and destination are the same file", + }, + } + + for modeName, mode := range confinementModes() { + for _, tt := range tests { + t.Run(modeName+"/"+tt.name, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + before := snapshotTree(t, workDir) + h := NewGRPCFileHandler(workDir, mode.opts...) + + resp := fileOp(t, h, mode.root, pb.FileOperationType_FILE_OPERATION_TYPE_COPY, func(r *pb.FileOperationRequest) { + r.Parameters = &pb.FileOperationRequest_CopyParams{ + CopyParams: &pb.CopyParams{Source: tt.source, Destination: tt.destination}, + } + }) + + assert.False(t, resp.GetSuccess()) + assert.Contains(t, resp.GetError(), tt.wantError) + assert.Equal(t, before, snapshotTree(t, workDir)) + }) + } + } +} diff --git a/internal/app/grpc/transfer_confinement_unix_test.go b/internal/app/grpc/transfer_confinement_unix_test.go index 23090d3..406ace8 100644 --- a/internal/app/grpc/transfer_confinement_unix_test.go +++ b/internal/app/grpc/transfer_confinement_unix_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "testing" + "github.com/gameap/daemon/internal/app/fsutil" pb "github.com/gameap/gameap/pkg/proto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -22,11 +23,16 @@ type fakeTransferService struct { payload []byte uploaded []byte uploads int + + // downloadCtx is the context the last download stream was opened with. + downloadCtx context.Context } func (f *fakeTransferService) DownloadFile( - _ context.Context, _ *pb.DownloadRequest, _ ...grpc.CallOption, + ctx context.Context, _ *pb.DownloadRequest, _ ...grpc.CallOption, ) (grpc.ServerStreamingClient[pb.DownloadChunk], error) { + f.downloadCtx = ctx + return &fakeDownloadStream{ fakeChunkReceiver: &fakeChunkReceiver{ chunks: []*pb.DownloadChunk{{Data: f.payload, IsFinal: true, ChecksumSha256: sha256Hex(f.payload)}}, @@ -279,3 +285,50 @@ func TestGRPCTransferHandler_PathOutsideTheRequestRoot(t *testing.T) { assert.Equal(t, "path is outside its confinement root", resp.GetError()) }) } + +// A gRPC stream is released by draining it or by ending its context. A task +// that fails after the stream is opened never drains it, so the handler has to +// end the context itself rather than leave the stream to the connection. +func TestGRPCTransferHandler_UploadTask_ReleasesTheDownloadStream(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + path string + wantSuccess bool + }{ + {name: "after_a_finished_download", path: "servers/a/uploaded.txt", wantSuccess: true}, + {name: "when_the_parent_directory_cannot_be_inspected", path: "servers/a/servers-link/b/planted.txt"}, + {name: "when_the_parent_directory_cannot_be_created", path: "servers/a/own.txt/uploaded.txt"}, + {name: "when_the_temp_file_cannot_be_opened", path: "servers/a/cstrike"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + if tt.path == "servers/a/cstrike" { + // The temp file name is taken by a directory. + require.NoError(t, os.Mkdir(filepath.Join(workDir, "servers", "a", "cstrike.tmp_tid"), 0o755)) + } + + sender := &fakeSender{} + service := &fakeTransferService{payload: []byte("uploaded payload")} + h := NewGRPCTransferHandler( + workDir, &FileTransferClient{client: service}, sender, 1, + fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"}), + ) + + ctx := t.Context() + + h.HandleFileUploadTask(ctx, "req", &pb.FileUploadTask{TransferId: "tid", Path: tt.path}) + + assert.Equal(t, tt.wantSuccess, transferResponse(t, sender).GetSuccess()) + + require.NotNil(t, service.downloadCtx, "the task has to get as far as opening the stream") + require.ErrorIs(t, service.downloadCtx.Err(), context.Canceled) + require.NoError(t, ctx.Err(), "the stream is released on its own, not by the connection going away") + }) + } +} diff --git a/internal/app/grpc/transfer_handler.go b/internal/app/grpc/transfer_handler.go index c2b4df1..c190ed0 100644 --- a/internal/app/grpc/transfer_handler.go +++ b/internal/app/grpc/transfer_handler.go @@ -128,8 +128,12 @@ func (h *GRPCTransferHandler) HandleFileUploadTask(ctx context.Context, requestI } defer h.sem.Release(1) - // Start download stream. - stream, err := h.fileTransfer.DownloadFileStream(ctx, task.TransferId, offset) + // The stream lives as long as its context: a return that never drains it + // would otherwise leave it open until the connection context ends. + streamCtx, cancelStream := context.WithCancel(ctx) + defer cancelStream() + + stream, err := h.fileTransfer.DownloadFileStream(streamCtx, task.TransferId, offset) if err != nil { l.WithError(err).Error("Failed to start download stream") h.sendResponse(requestID, false, errors.Wrap(err, "filetransfer service unavailable").Error()) diff --git a/test/functional/serverscommand/install/install_test.go b/test/functional/serverscommand/install/install_test.go index 5216c3e..f6f1ef8 100644 --- a/test/functional/serverscommand/install/install_test.go +++ b/test/functional/serverscommand/install/install_test.go @@ -25,7 +25,7 @@ func (suite *Suite) TestInstall_InstallFromRemoteRepository_GameInstalled() { server := suite.GivenServerForGameAndMod( domain.Game{ StartCode: "cstrike", - RemoteRepository: "https://files.gameap.ru/test/test.tar.xz", + RemoteRepository: "https://cdn.gameap.com/test/test.tar.xz", }, domain.GameMod{ Name: "public", @@ -45,11 +45,11 @@ func (suite *Suite) TestInstall_InstallFromRemoteRepository_GameAndModInstalled( server := suite.GivenServerForGameAndMod( domain.Game{ StartCode: "cstrike", - RemoteRepository: "https://files.gameap.ru/test/test.tar.xz", + RemoteRepository: "https://cdn.gameap.com/test/test.tar.xz", }, domain.GameMod{ Name: "public", - RemoteRepository: "https://files.gameap.ru/mod-game.tar.gz", + RemoteRepository: "https://cdn.gameap.com/mod-game.tar.gz", }, ) server.SetInstallationStatus(domain.ServerNotInstalled) @@ -66,12 +66,12 @@ func (suite *Suite) TestInstall_InstallFromLocalRepository_GameAndModInstalledFr server := suite.GivenServerForGameAndMod( domain.Game{ StartCode: "cstrike", - RemoteRepository: "https://files.gameap.ru/test/test.tar.xz", + RemoteRepository: "https://cdn.gameap.com/test/test.tar.xz", LocalRepository: filepath.Join(suite.WorkPath, "repository", "game.tar.gz"), }, domain.GameMod{ Name: "public", - RemoteRepository: "https://files.gameap.ru/mod-game.tar.gz", + RemoteRepository: "https://cdn.gameap.com/mod-game.tar.gz", LocalRepository: filepath.Join(suite.WorkPath, "repository", "game_mod.tar.gz"), }, ) From 1544e208c38183d8d23fbf70475f189b976834a9 Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 17 Nov 2026 20:36:25 +0100 Subject: [PATCH 3/7] review fixes --- internal/app/archive/archiver.go | 11 +- internal/app/archive/confine_unix_test.go | 165 ++++++ internal/app/archive/create.go | 151 +++-- internal/app/archive/create_test.go | 26 +- internal/app/fsutil/confine.go | 521 +++++++++++++----- internal/app/fsutil/confine_test.go | 157 +++++- internal/app/fsutil/confine_unix_test.go | 332 ++++++++++- internal/app/fsutil/copy.go | 86 ++- internal/app/fsutil/copy_test.go | 37 ++ internal/app/fsutil/copy_unix_test.go | 68 +++ .../app/grpc/file_confinement_unix_test.go | 75 +++ 11 files changed, 1399 insertions(+), 230 deletions(-) diff --git a/internal/app/archive/archiver.go b/internal/app/archive/archiver.go index 6d043a3..5e45b8e 100644 --- a/internal/app/archive/archiver.go +++ b/internal/app/archive/archiver.go @@ -11,11 +11,12 @@ // // A request acting for the node may start above the game server directories. // Create holds to the same boundary there: every source is placed on its own, -// and a game server directory entered while a larger tree is packed is read -// through a root opened at it. Extract does not: an archive unpacked above the -// game server directories is written through the root of its destination -// alone, so an entry naming a path inside one of them is followed through the -// links standing there, as far as the destination reaches. +// a game server directory entered while a larger tree is packed is read +// through a root opened at it, and a link followed from above is read in the +// game server directory it ends in. Extract does not: an archive unpacked +// above the game server directories is written through the root of its +// destination alone, so an entry naming a path inside one of them is followed +// through the links standing there, as far as the destination reaches. // // Extraction feeds attacker-controlled bytes to third-party format decoders, // so the caller is expected to run it under a recover (see the gRPC archive diff --git a/internal/app/archive/confine_unix_test.go b/internal/app/archive/confine_unix_test.go index 655ff4f..21c957b 100644 --- a/internal/app/archive/confine_unix_test.go +++ b/internal/app/archive/confine_unix_test.go @@ -6,8 +6,10 @@ import ( "archive/zip" "context" "io" + "maps" "os" "path/filepath" + "slices" "testing" "github.com/gameap/daemon/internal/app/fsutil" @@ -649,6 +651,169 @@ func TestCreate_SourcesAboveTheServerDirs(t *testing.T) { }) } +// A node-level link need not lead to a game server directory itself: it can end +// in the middle of one, at a directory that is no boundary. What is read +// through it still is that server's tree, so the links its tenant keeps there +// are followed inside the game server directory and nowhere else. +func TestCreate_NodeLinkIntoTheMiddleOfAServer(t *testing.T) { + t.Parallel() + + opts := []fsutil.ConfineOption{fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})} + + // newTree leaves server "a" with the links that stay inside it and adds + // the node-level links into it. + newTree := func(t *testing.T) string { + t.Helper() + + workDir := tenantWorkDir(t) + for _, link := range []string{"servers-link", "node-link", "file-link"} { + require.NoError(t, os.Remove(filepath.Join(workDir, "servers", "a", link))) + } + + writeTree(t, workDir, map[string]string{"shortcuts/.keep": ""}) + require.NoError(t, os.Symlink("../servers/a/cstrike", filepath.Join(workDir, "shortcuts", "current"))) + require.NoError(t, os.Symlink("../own.txt", filepath.Join(workDir, "servers", "a", "cstrike", "inside"))) + + return workDir + } + + requests := map[string]*pb.CreateArchiveParams{ + "directory_holding_the_link": {BasePath: ".", Sources: []string{"shortcuts"}}, + "link_named_as_a_source": {BasePath: ".", Sources: []string{"shortcuts/current"}}, + "link_below_the_base_path": {BasePath: "shortcuts", Sources: []string{"current"}}, + "link_named_as_the_base": {BasePath: "shortcuts/current", Sources: []string{"."}}, + "whole_work_directory": {BasePath: "", Sources: []string{"shortcuts", "steamcmd"}}, + } + + for name, params := range requests { + t.Run("link_to_the_neighbour_is_refused/"+name, func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + require.NoError(t, os.Symlink( + "../../b/cstrike/server.cfg", filepath.Join(workDir, "servers", "a", "cstrike", "leak"), + )) + + neighbour := readTree(t, filepath.Join(workDir, "servers", "b")) + + res, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: params.GetBasePath(), + Sources: params.GetSources(), + FollowSymlinks: true, + }, nil, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, res) + assert.Equal(t, neighbour, readTree(t, filepath.Join(workDir, "servers", "b"))) + + _, statErr := os.Lstat(filepath.Join(workDir, "backups", "node.zip")) + assert.ErrorIs(t, statErr, os.ErrNotExist, "a refused operation leaves no archive behind") + }) + + t.Run("links_staying_inside_the_server_are_followed/"+name, func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: params.GetBasePath(), + Sources: params.GetSources(), + FollowSymlinks: true, + }, nil, opts...) + require.NoError(t, err) + + bodies := slices.Collect(maps.Values(zipContents(t, filepath.Join(workDir, "backups", "node.zip")))) + + assert.Contains(t, bodies, "hostname a", "the server file behind the link") + assert.Contains(t, bodies, "own", "the file a link inside the server leads to") + assert.NotContains(t, bodies, "rcon_password secret") + }) + } + + t.Run("file_link_led_on_by_the_tenant_is_refused", func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + require.NoError(t, os.Symlink("../servers/a/redirect.cfg", filepath.Join(workDir, "shortcuts", "config"))) + require.NoError(t, os.Symlink("../b/cstrike/server.cfg", filepath.Join(workDir, "servers", "a", "redirect.cfg"))) + + res, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: ".", + Sources: []string{"shortcuts/config"}, + FollowSymlinks: true, + }, nil, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, res) + }) + + t.Run("link_is_packed_as_a_link_when_links_are_not_followed", func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + require.NoError(t, os.Symlink("a", filepath.Join(workDir, "servers", "alias"))) + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: ".", + Sources: []string{"shortcuts/current", "servers/alias"}, + }, nil, opts...) + + require.NoError(t, err) + assert.ElementsMatch( + t, []string{"shortcuts/current", "servers/alias"}, + zipEntryNames(t, filepath.Join(workDir, "backups", "node.zip")), + ) + }) +} + +// A walk lasts, and a game server directory can be removed and created again +// while it does. The directory the walk then enters under that name confines +// what is read below it, however long ago the walk first looked. +func TestSourceWalker_ServerDirReplacedDuringTheWalk(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + for _, link := range []string{"servers-link", "node-link", "file-link"} { + require.NoError(t, os.Remove(filepath.Join(workDir, "servers", "a", link))) + } + + confiner := fsutil.NewConfiner(workDir, fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})) + + base, err := confiner.Resolve(".", fsutil.TargetTree) + require.NoError(t, err) + defer base.Close() + + w := &sourceWalker{ + ctx: context.Background(), + confiner: confiner, + limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, + } + defer w.close() + + _, err = w.collect(base, ".", []string{"steamcmd"}) + require.NoError(t, err) + + former, err := os.Stat(filepath.Join(workDir, "servers", "b")) + require.NoError(t, err) + require.True(t, confiner.IsServerDir(former)) + + require.NoError(t, os.Rename(filepath.Join(workDir, "servers", "b"), filepath.Join(workDir, "removed-b"))) + require.NoError(t, os.Mkdir(filepath.Join(workDir, "servers", "b"), 0o755)) + require.NoError(t, os.Symlink("../a/own.txt", filepath.Join(workDir, "servers", "b", "leak"))) + + entries, err := w.collect(base, ".", []string{"servers"}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Empty(t, entries) +} + // Many sources, and many links to one game server directory, are read through // the roots already open: the walk must not hold a descriptor for each. func TestSourceWalker_SharesRoots(t *testing.T) { diff --git a/internal/app/archive/create.go b/internal/app/archive/create.go index 83ab0fa..ccb2142 100644 --- a/internal/app/archive/create.go +++ b/internal/app/archive/create.go @@ -212,23 +212,31 @@ type walkLimits struct { // symlinks unless follow is set, in which case the symlink target contents are // archived. // -// Every source is placed by the confiner on its own, and a game server -// directory the walk enters from above is read through a root opened at it. -// A tree packed for the node is thus confined the way a tree packed for one -// game server is: os.Root refuses a link leading out of the game server -// directory it stands in, whichever directory the request started from. +// Every source is placed by the confiner on its own, and the walk keeps to the +// same boundary as it goes: a game server directory it enters from above is +// read through a root opened at it, and a link it follows from above is read +// where the link ends, in the game server directory that place lies in. A tree +// packed for the node is thus confined the way a tree packed for one game +// server is: os.Root refuses a link leading out of the game server directory +// it stands in, whichever directory the request started from. type sourceWalker struct { ctx context.Context confiner *fsutil.Confiner limits *walkLimits entries []sourceEntry - scopes []sourceScope + scopes []*sourceScope } // sourceScope is a root the sources are read through. type sourceScope struct { root *os.Root dir os.FileInfo + // path is where root stands, relative to the work directory. + path string + // confined is set for a root standing in a game server directory. Nothing + // read through it leads out of that directory, so the walk looks for no + // further boundary below it. + confined bool // owned roots are opened by the walker and closed with it. owned bool } @@ -250,7 +258,7 @@ func (w *sourceWalker) collect(base *fsutil.Confined, basePath string, sources [ return nil, err } - if _, err := w.adopt(base.Root, false); err != nil { + if _, err := w.adopt(base, false); err != nil { return nil, err } @@ -260,17 +268,25 @@ func (w *sourceWalker) collect(base *fsutil.Confined, basePath string, sources [ return nil, errors.Wrapf(err, "invalid source %q", src) } - placed, err := w.confiner.Resolve(path.Join(baseRel, srcRel), fsutil.TargetTree) + // The base path is a directory to pack from. Anything else is an entry + // of it: a link is packed as a link unless the request has links + // followed, and a directory is entered by the walk like any other. + target := fsutil.TargetEntry + if srcRel == "." { + target = fsutil.TargetTree + } + + placed, err := w.confiner.Resolve(path.Join(baseRel, srcRel), target) if err != nil { return nil, err } - root, err := w.adopt(placed.Root, true) + scope, err := w.adopt(placed, true) if err != nil { return nil, err } - if err := w.walk(root, placed.Rel, srcRel, 0); err != nil { + if err := w.walk(scope, placed.Rel, srcRel, 0); err != nil { return nil, err } } @@ -278,37 +294,48 @@ func (w *sourceWalker) collect(base *fsutil.Confined, basePath string, sources [ return w.entries, nil } -// adopt returns the root to read the directory of root through: the one -// already open there, or root itself, which is then kept. The sources of one -// request mostly share a directory, and a link can lead to a game server -// directory any number of times; neither may cost a descriptor each. -func (w *sourceWalker) adopt(root *os.Root, owned bool) (*os.Root, error) { - dir, err := root.Stat(".") +// adopt returns the scope to read the directory of placed through: the one +// already open there, or one made of placed, whose root is then kept. The +// sources of one request mostly share a directory, and a link can lead to a +// game server directory any number of times; neither may cost a descriptor +// each. +func (w *sourceWalker) adopt(placed *fsutil.Confined, owned bool) (*sourceScope, error) { + dir, err := placed.Root.Stat(".") if err != nil { if owned { - _ = root.Close() + _ = placed.Root.Close() } - return nil, errors.Wrap(err, "failed to stat source directory") + return nil, errors.Wrapf(err, "failed to stat source directory %q", placed.Scope) } if known := w.scopeOf(dir); known != nil { if owned { - _ = root.Close() + _ = placed.Root.Close() } + known.confined = known.confined || placed.InServerDir + return known, nil } - w.scopes = append(w.scopes, sourceScope{root: root, dir: dir, owned: owned}) + scope := &sourceScope{ + root: placed.Root, + dir: dir, + path: placed.Scope, + confined: placed.InServerDir, + owned: owned, + } + + w.scopes = append(w.scopes, scope) - return root, nil + return scope, nil } -func (w *sourceWalker) scopeOf(dir os.FileInfo) *os.Root { +func (w *sourceWalker) scopeOf(dir os.FileInfo) *sourceScope { for _, scope := range w.scopes { if os.SameFile(scope.dir, dir) { - return scope.root + return scope } } @@ -343,11 +370,13 @@ func copySource(root *os.Root, rel string, w io.Writer, bytesLeft int64) (int64, return n, nil } -func (w *sourceWalker) walk(root *os.Root, rel, name string, symlinkDepth int) error { +func (w *sourceWalker) walk(scope *sourceScope, rel, name string, symlinkDepth int) error { if err := w.ctx.Err(); err != nil { return errors.Wrap(err, "create archive canceled") } + root := scope.root + info, err := root.Lstat(rel) if err != nil { return errors.Wrapf(err, "failed to stat source %q", rel) @@ -373,11 +402,20 @@ func (w *sourceWalker) walk(root *os.Root, rel, name string, symlinkDepth int) e if os.SameFile(info, w.limits.archive) { return nil } + + into, intoRel, err := w.cross(scope, rel) + if err != nil { + return err + } + + if into != nil { + return w.walk(into, intoRel, name, symlinkDepth) + } } switch { case info.IsDir(): - return w.walkDir(root, rel, name, info, symlinkDepth) + return w.walkDir(scope, rel, name, info, symlinkDepth) case info.Mode()&os.ModeSymlink != 0: link, err := root.Readlink(rel) if err != nil { @@ -394,12 +432,45 @@ func (w *sourceWalker) walk(root *os.Root, rel, name string, symlinkDepth int) e } } -func (w *sourceWalker) walkDir(root *os.Root, rel, name string, info os.FileInfo, symlinkDepth int) error { - root, rel, err := w.enter(root, rel, info) +// cross returns where to go on reading what the followed link rel of scope +// leads to, when that lies behind a boundary: the scope of the game server +// directory the link ends in and the path there. A link that crosses no +// boundary is read through the root it stands in, and nothing is returned. +// +// The root of scope would follow the link wherever it leads below it, into the +// middle of a game server directory as well, and the links the tenant keeps +// there would then be followed through that root too, out of the game server +// directory again. +func (w *sourceWalker) cross(scope *sourceScope, rel string) (*sourceScope, string, error) { + if scope.confined { + return nil, "", nil + } + + placed, err := w.confiner.Resolve(path.Join(scope.path, rel), fsutil.TargetTree) + if err != nil { + return nil, "", err + } + + into, err := w.adopt(placed, true) + if err != nil { + return nil, "", err + } + + if into == scope { + return nil, "", nil + } + + return into, placed.Rel, nil +} + +func (w *sourceWalker) walkDir(scope *sourceScope, rel, name string, info os.FileInfo, symlinkDepth int) error { + scope, rel, err := w.enter(scope, rel, info) if err != nil { return err } + root := scope.root + // The "." source contributes its children only; storing "." itself would // produce a useless root entry. if name != "." { @@ -419,7 +490,7 @@ func (w *sourceWalker) walkDir(root *os.Root, rel, name string, info os.FileInfo childName = path.Join(name, child.Name()) } - if err := w.walk(root, path.Join(rel, child.Name()), childName, symlinkDepth); err != nil { + if err := w.walk(scope, path.Join(rel, child.Name()), childName, symlinkDepth); err != nil { return err } } @@ -427,33 +498,31 @@ func (w *sourceWalker) walkDir(root *os.Root, rel, name string, info os.FileInfo return nil } -// enter returns where to read the directory rel of root from. A game server +// enter returns where to read the directory rel of scope from. A game server // directory is read through a root of its own from there on; any other // directory stays where it is. -func (w *sourceWalker) enter(root *os.Root, rel string, info os.FileInfo) (*os.Root, string, error) { - if rel == "." || !w.confiner.IsServerDir(info) { - return root, rel, nil +func (w *sourceWalker) enter(scope *sourceScope, rel string, info os.FileInfo) (*sourceScope, string, error) { + if scope.confined || rel == "." || !w.confiner.IsServerDir(info) { + return scope, rel, nil } if known := w.scopeOf(info); known != nil { - // A link back to the directory the walk is already confined to keeps - // its path, and with it the limit os.Root puts on a chain of links. - if known == root { - return root, rel, nil - } + known.confined = true return known, ".", nil } - inner, err := root.OpenRoot(rel) + dir := path.Join(scope.path, rel) + + inner, err := scope.root.OpenRoot(rel) if err != nil { - return nil, "", errors.Wrapf(err, "failed to open game server directory %q", rel) + return nil, "", errors.Wrapf(err, "failed to open game server directory %q", dir) } - inner, err = w.adopt(inner, true) + into, err := w.adopt(&fsutil.Confined{Root: inner, Rel: ".", Scope: dir, InServerDir: true}, true) if err != nil { return nil, "", err } - return inner, ".", nil + return into, ".", nil } diff --git a/internal/app/archive/create_test.go b/internal/app/archive/create_test.go index 52dc52d..28fa7bb 100644 --- a/internal/app/archive/create_test.go +++ b/internal/app/archive/create_test.go @@ -549,17 +549,22 @@ func TestWalkSourceSymlinkDepthLimit(t *testing.T) { writeTree(t, workDir, map[string]string{"src/file.txt": "data"}) require.NoError(t, os.Symlink(".", filepath.Join(workDir, "src", "loop"))) - root, err := os.OpenRoot(workDir) + confiner := fsutil.NewConfiner(workDir) + + base, err := confiner.Resolve(".", fsutil.TargetTree) require.NoError(t, err) - defer root.Close() + defer base.Close() w := &sourceWalker{ ctx: context.Background(), - confiner: fsutil.NewConfiner(workDir), + confiner: confiner, limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, } - err = w.walk(root, "src/loop", "src/loop", maxFollowDepth) + scope, err := w.adopt(base, false) + require.NoError(t, err) + + err = w.walk(scope, "src/loop", "src/loop", maxFollowDepth) require.Error(t, err) assert.Contains(t, err.Error(), "symlink nesting too deep") } @@ -611,17 +616,22 @@ func TestSourceWalkerRespectsContext(t *testing.T) { workDir := t.TempDir() writeTree(t, workDir, map[string]string{"src/a.txt": "a"}) - root, err := os.OpenRoot(workDir) + confiner := fsutil.NewConfiner(workDir) + + base, err := confiner.Resolve(".", fsutil.TargetTree) require.NoError(t, err) - defer root.Close() + defer base.Close() w := &sourceWalker{ ctx: canceledContext(t), - confiner: fsutil.NewConfiner(workDir), + confiner: confiner, limits: &walkLimits{maxEntries: defaultMaxFilesLimit()}, } - err = w.walk(root, "src", "src", 0) + scope, err := w.adopt(base, false) + require.NoError(t, err) + + err = w.walk(scope, "src", "src", 0) require.ErrorIs(t, err, context.Canceled) } diff --git a/internal/app/fsutil/confine.go b/internal/app/fsutil/confine.go index 457a870..e78f3e3 100644 --- a/internal/app/fsutil/confine.go +++ b/internal/app/fsutil/confine.go @@ -1,10 +1,12 @@ package fsutil import ( + "cmp" "os" + "path" + "path/filepath" "slices" "strings" - "sync" "github.com/pkg/errors" ) @@ -27,7 +29,9 @@ const ( TargetEntry Target = iota // TargetTree is for operations that work inside the named directory: they // list or walk it, or create entries below it. A game server directory - // named this way confines the operation. + // named this way confines the operation, and so does one a link in the + // last component leads into: the path is then placed where the link ends. + // A link that crosses no boundary is left to the operation as it is named. TargetTree ) @@ -83,23 +87,33 @@ func WithRoot(root string) ConfineOption { // in its own path is refused, including one the tenant of an outer game server // puts in place of a directory nested in its own. // -// A boundary is a directory, not a name. A path may spell a game server -// directory or the request root unlike the daemon does: in another letter case -// on a case-insensitive volume, by a Windows short name, through a link -// standing next to it. Such a path is placed by the directory it leads to. +// A boundary is a directory, not a name. A path can reach a game server +// directory or the request root without spelling it the way the daemon does: +// in another letter case on a case-insensitive volume, by a Windows short +// name, through a link standing anywhere above it, or through a link that +// leads into the middle of it. A path that does not spell a game server +// directory out is therefore walked down from the work directory one component +// at a time. Every directory on the way is compared with the boundaries as +// they are on disk at that moment, and every link is replaced by what it leads +// to, so the path ends up in the directory it really lies in. A boundary found +// this way is compared as it was opened: the directory the request goes on in +// is the one that was checked, whatever its name leads to a moment later. +// +// A path that does spell a game server directory the way the daemon knows it +// is placed by that spelling alone, without a lookup, and os.Root keeps the +// rest of it inside. The walk would add nothing there unless game server +// directories are nested in one another and the path reaches a second one of +// them under another name. // // Resolve places the path a request names, and nothing below it. An operation // that walks a tree from above the game server directories, as a request // acting for the node rather than for one server can, crosses into them // through the root it started with unless it asks IsServerDir about the -// directories it enters. +// directories it enters and Resolve about the links it follows. type Confiner struct { workDir string serverDirs ServerDirLister root string - - identify sync.Once - identities []os.FileInfo } // NewConfiner creates a Confiner anchored at workDir. @@ -121,6 +135,9 @@ type Confined struct { // Scope is the directory Root is opened at, relative to the work directory // ("." for the work directory itself). Scope string + // InServerDir is set when Root stands at a game server directory or below + // one. Whatever is reached through such a root stays in that directory. + InServerDir bool } func (c *Confined) Close() error { @@ -148,37 +165,24 @@ func (c *Confined) SameRoot(other *Confined) bool { // IsServerDir reports whether info describes a game server directory. A walk // that starts above the game server directories uses it to notice the ones it // enters, which no request path names. +// +// The game server directories are looked up on every call. A walk lasts long +// enough for one of them to be removed and created again, and the directory +// found under its name then is not the one that stood there when the walk +// began. func (c *Confiner) IsServerDir(info os.FileInfo) bool { - if c.serverDirs == nil || !info.IsDir() { + names := c.serverNames() + if len(names) == 0 || !info.IsDir() { return false } - c.identify.Do(func() { - root, err := os.OpenRoot(c.workDir) - if err != nil { - return - } - defer root.Close() - - for _, serverDir := range c.serverDirs.ServerDirs() { - dir, err := RootRel(serverDir) - if err != nil || dir == "." { - continue - } - - if known, err := root.Stat(dir); err == nil && known.IsDir() { - c.identities = append(c.identities, known) - } - } - }) - - for _, known := range c.identities { - if os.SameFile(info, known) { - return true - } + work, err := os.OpenRoot(c.workDir) + if err != nil { + return false } + defer work.Close() - return false + return isOneOf(info, onDisk(work, names)) } // Resolve places a caller-supplied path. See Confiner for the model. @@ -188,20 +192,120 @@ func (c *Confiner) Resolve(p string, target Target) (*Confined, error) { return nil, err } - boundaries, err := c.boundaries(rel, target) + b, err := c.bounds() if err != nil { return nil, err } - root, err := os.OpenRoot(c.workDir) + work, err := os.OpenRoot(c.workDir) if err != nil { return nil, errors.Wrap(err, "work directory unavailable") } - scope := "." + if named, settled := b.named(rel, target); settled { + return openNamed(work, rel, named) + } + + return walk(work, b, rel, target) +} + +// bounds are the directories one request is confined by, spelled the way the +// daemon knows them. +type bounds struct { + servers []string + // root is the request root. It is empty when the request names none, or + // names the work directory, which confines every path already. + root string +} + +func (c *Confiner) bounds() (bounds, error) { + b := bounds{servers: c.serverNames()} + + if c.root == "" { + return b, nil + } + + root, err := RootRel(c.root) + if err != nil { + return bounds{}, err + } + + if root != "." { + b.root = root + } + + return b, nil +} + +// serverNames returns the game server directories that can be a boundary: a +// name the work directory cannot hold, or the work directory itself, is none. +func (c *Confiner) serverNames() []string { + if c.serverDirs == nil { + return nil + } + + var names []string + + for _, serverDir := range c.serverDirs.ServerDirs() { + if dir, err := RootRel(serverDir); err == nil && dir != "." { + names = append(names, dir) + } + } + + return names +} + +// boundary is a leading part of a request path that names a directory the +// path is confined by. +type boundary struct { + end int + server bool +} + +// named returns the boundaries rel spells out, outermost first, and whether +// they settle where rel belongs: it names a game server directory, if the +// daemon knows any, and lies in the request root, if the request has one. +func (b bounds) named(rel string, target Target) ([]boundary, bool) { + var found []boundary + + inRoot := b.root == "" + if !inRoot && below(rel, b.root) { + inRoot = true + + found = append(found, boundary{end: len(b.root), server: slices.Contains(b.servers, b.root)}) + } + + inServer := len(b.servers) == 0 + + for _, dir := range b.servers { + // An entry named as such belongs to the directory holding it. + if !below(rel, dir) || (rel == dir && target != TargetTree) { + continue + } + + inServer = true + + found = append(found, boundary{end: len(dir), server: true}) + } + + // Every boundary is a leading part of rel, so ordering by length puts an + // enclosing directory before the one nested in it. + slices.SortFunc(found, func(x, y boundary) int { return cmp.Compare(x.end, y.end) }) + + found = slices.CompactFunc(found, func(x, y boundary) bool { return x.end == y.end }) + + return found, inRoot && inServer +} + +// openNamed opens the boundaries rel spells out, each from inside the one +// before it. +func openNamed(work *os.Root, rel string, named []boundary) (*Confined, error) { + placed := &Confined{Root: work, Scope: "."} + + for _, bound := range named { + dir := rel[:bound.end] - for _, dir := range boundaries { - next, err := root.OpenRoot(relativeTo(dir, scope)) + next, err := placed.Root.OpenRoot(relativeTo(dir, placed.Scope)) if err != nil { // A boundary that is not on disk yet holds nothing a tenant could // have planted: whatever the operation creates below it is created @@ -210,160 +314,313 @@ func (c *Confiner) Resolve(p string, target Target) (*Confined, error) { break } - _ = root.Close() + _ = placed.Root.Close() return nil, errors.Wrapf(err, "failed to open confinement directory %q", dir) } - _ = root.Close() - root, scope = next, dir + _ = placed.Root.Close() + + placed.Root, placed.Scope = next, dir + placed.InServerDir = placed.InServerDir || bound.server } - return &Confined{Root: root, Rel: relativeTo(rel, scope), Scope: scope}, nil + placed.Rel = relativeTo(rel, placed.Scope) + + return placed, nil +} + +// maxLinkHops bounds the links one path is led through while it is placed. +// os.Root gives up on a single name long before that; the limit is for a tree +// that keeps changing underneath the walk. +const maxLinkHops = 64 + +// placer walks a request path down from the work directory and moves into +// every boundary the path passes. +type placer struct { + // servers and reqRoot are the boundaries as they are on disk. reqRoot is + // nil when the request names no root or the root is not there. + servers []os.FileInfo + reqRoot os.FileInfo + + // root is the innermost boundary reached, opened at scope. + root *os.Root + scope string + // at is where the walk stands inside root. No link is left in it. + at string + + inRoot bool + inServer bool + hops int } -// boundaries returns the directories that confine rel, outermost first. Each -// is spelled the way rel spells it, so the directory opened is the one the -// request names even where the file system compares names loosely. -func (c *Confiner) boundaries(rel string, target Target) ([]string, error) { - var lengths []int +// walk places a path that does not spell its boundaries out. +func walk(work *os.Root, b bounds, rel string, target Target) (*Confined, error) { + p := &placer{root: work, scope: ".", at: "."} - if c.root != "" { - root, err := RootRel(c.root) + var names []string + + if rel != "." { + names = strings.Split(rel, "/") + p.servers = onDisk(work, b.servers) + + if b.root != "" { + if dirs := onDisk(work, []string{b.root}); len(dirs) > 0 { + p.reqRoot = dirs[0] + } + } + } + + for i, name := range names { + moved, err := p.step(name, i == len(names)-1, target) if err != nil { + _ = p.root.Close() + return nil, err } - // The work directory already confines every path. - if root != "." { - n := leadingLen(rel, root) - if n == 0 || !c.sameDir(rel[:n], root) { - return nil, ErrPathOutsideConfinement - } + if !moved { + p.at = path.Join(p.at, strings.Join(names[i:], "/")) - lengths = append(lengths, n) + break } } - if c.serverDirs != nil { - lengths = c.serverBoundaries(rel, target, lengths) + // A request root that is spelled out but not on disk yet has nothing in it + // to keep the request from, like any other boundary that is not there. + if b.root != "" && !p.inRoot && !below(rel, b.root) { + _ = p.root.Close() + + return nil, ErrPathOutsideConfinement } - // Every match is a leading part of rel, so ordering by length puts an - // enclosing directory before the one nested in it. - slices.Sort(lengths) - lengths = slices.Compact(lengths) + return &Confined{Root: p.root, Rel: p.at, Scope: p.scope, InServerDir: p.inServer}, nil +} - dirs := make([]string, 0, len(lengths)) - for _, n := range lengths { - dirs = append(dirs, rel[:n]) +// step takes the walk one component of the request path further and reports +// whether it got there. Where it did not, the rest of the path is left the way +// the request spells it, for os.Root to resolve from where the walk stands. +func (p *placer) step(name string, last bool, target Target) (bool, error) { + // No boundary is left to be found. + if len(p.servers) == 0 && (p.reqRoot == nil || p.inRoot) { + return false, nil } - return dirs, nil + switch { + case !last: + return p.take(name) + case target == TargetTree: + return p.tree(name) + default: + return p.entry(name) + } } -// serverBoundaries adds the leading parts of rel that are game server -// directories to lengths. -func (c *Confiner) serverBoundaries(rel string, target Target, lengths []int) []int { - // Leading parts as deep as a game server directory but spelled unlike it. - var loose []int +// take moves into name, an entry of the directory the walk stands in, with +// every link it leads through followed by hand. It reports false, and has +// moved nowhere, when name itself is nothing to move into: it is missing, or a +// link os.Root does not follow from here. What goes wrong further along a link +// is an error: the path leads somewhere, and not to a place it may be in. +func (p *placer) take(name string) (bool, error) { + queue := []string{name} + linked := false + + for len(queue) > 0 { + part := queue[0] + queue = queue[1:] + + switch part { + case "", ".": + continue + case "..": + // Only a link that has led into a boundary gets here: one that + // leaves the root it starts in is not followed in the first place. + if p.at == "." { + return false, errors.Errorf("failed to follow link %q: it leads back out of %q", name, p.scope) + } + + p.at = path.Dir(p.at) - for _, serverDir := range c.serverDirs.ServerDirs() { - dir, err := RootRel(serverDir) - if err != nil || dir == "." { continue } - n := leadingLen(rel, dir) - // An entry named as such belongs to the directory holding it. - if n == 0 || (n == len(rel) && target != TargetTree) { + next := path.Join(p.at, part) + + info, err := p.root.Lstat(next) + if err == nil && info.Mode()&os.ModeSymlink != 0 { + // What os.Root does not follow from here is not followed by hand + // either: a dangling link, an absolute one, and above all one that + // leads out of the root, so that no boundary is left this way. + _, err = p.root.Stat(next) + } + + if err != nil { + if !linked { + return false, nil + } + + return false, errors.Wrapf(err, "failed to follow link %q", name) + } + + if info.Mode()&os.ModeSymlink != 0 { + target, err := p.readLink(next) + if err != nil { + return false, errors.WithMessagef(err, "failed to follow link %q", name) + } + + queue = append(strings.Split(filepath.ToSlash(target), "/"), queue...) + linked = true + continue } - if rel[:n] == dir { - lengths = append(lengths, n) - } else { - loose = append(loose, n) + if !info.IsDir() { + p.at = next + + continue } - } - slices.Sort(loose) + // "dir/.." is the directory the walk stands in already: a path that + // only passes a boundary by has not entered it. + if len(queue) > 0 && queue[0] == ".." { + queue = queue[1:] - // The usual request spells its game server directory the way the daemon - // knows it and is settled above without touching the disk. What is left - // may still be one under another spelling, which only the disk can tell. - for _, n := range slices.Compact(loose) { - if slices.Contains(lengths, n) { continue } - if info, err := c.stat(rel[:n]); err == nil && c.IsServerDir(info) { - lengths = append(lengths, n) + p.at = next + + if err := p.cross(info); err != nil { + return false, err } } - return lengths + return true, nil } -// leadingLen returns the length of the leading part of rel that is as deep as -// dir, or 0 when rel is not that deep. -func leadingLen(rel, dir string) int { - if rel == "." { - return 0 +func (p *placer) readLink(name string) (string, error) { + if p.hops++; p.hops > maxLinkHops { + return "", errors.Errorf("more than %d links on the way", maxLinkHops) } - end := 0 + target, err := p.root.Readlink(name) + if err != nil { + return "", errors.Wrapf(err, "failed to read link %q", name) + } - for range strings.Count(dir, "/") + 1 { - if end == len(rel) { - return 0 - } + return target, nil +} - if end > 0 { - end++ - } +// tree moves into the last component when the operation works inside it and a +// boundary lies on the way there. Otherwise the component is left as named: an +// operation that meets a link there deals with the link. +func (p *placer) tree(name string) (bool, error) { + root, at := p.root, p.at - next := strings.IndexByte(rel[end:], '/') - if next < 0 { - end = len(rel) - } else { - end += next - } + moved, err := p.take(name) + if err != nil || !moved { + return false, err } - return end + if p.root == root { + p.at = at + + return false, nil + } + + return true, nil } -// sameDir reports whether two names lead to one directory of the work -// directory. Names spelled alike do without a lookup, which also covers a -// directory that is not on disk yet. -func (c *Confiner) sameDir(a, b string) bool { - if a == b { - return true +// entry leaves the last component to the operation, which acts on it as an +// entry of the directory the walk stands in. Only the request root is moved +// into: named as an entry, it still is the directory the request is kept in. +func (p *placer) entry(name string) (bool, error) { + if p.reqRoot == nil || p.inRoot { + return false, nil } - infoA, err := c.stat(a) - if err != nil || !infoA.IsDir() { - return false + info, err := p.root.Stat(path.Join(p.at, name)) + if err != nil || !os.SameFile(info, p.reqRoot) { + return false, nil } - infoB, err := c.stat(b) - if err != nil { - return false + moved, err := p.take(name) + if err != nil || !moved { + return false, err + } + + if !p.inRoot { + return false, errors.Errorf("request root named by %q was replaced while the path was being placed", name) } - return os.SameFile(infoA, infoB) + return true, nil } -// stat describes what a name relative to the work directory leads to. -func (c *Confiner) stat(name string) (os.FileInfo, error) { - root, err := os.OpenRoot(c.workDir) +// cross moves the walk into the directory it stands at when that directory is +// a boundary. info describes the directory as it was found by name. +func (p *placer) cross(info os.FileInfo) error { + isRoot := p.reqRoot != nil && os.SameFile(info, p.reqRoot) + isServer := isOneOf(info, p.servers) + + if !isRoot && !isServer { + return nil + } + + dir := path.Join(p.scope, p.at) + + inner, err := p.root.OpenRoot(p.at) if err != nil { - return nil, err + return errors.Wrapf(err, "failed to open confinement directory %q", dir) + } + + // The name was looked at before it was opened and may lead elsewhere by + // now. What counts is the directory in hand: the request goes on in it + // only if it is the one that was found to be the boundary. + opened, err := inner.Stat(".") + if err != nil { + _ = inner.Close() + + return errors.Wrapf(err, "failed to stat confinement directory %q", dir) } - defer root.Close() - return root.Stat(name) + if !os.SameFile(opened, info) { + _ = inner.Close() + + return errors.Errorf("confinement directory %q was replaced while it was being opened", dir) + } + + _ = p.root.Close() + + p.root, p.scope, p.at = inner, dir, "." + p.inRoot = p.inRoot || isRoot + p.inServer = p.inServer || isServer + + return nil +} + +// onDisk describes the directories the names lead to at this moment. A name +// that leads to none confines nothing. +func onDisk(work *os.Root, names []string) []os.FileInfo { + var dirs []os.FileInfo + + for _, name := range names { + if info, err := work.Stat(name); err == nil && info.IsDir() { + dirs = append(dirs, info) + } + } + + return dirs +} + +func isOneOf(info os.FileInfo, dirs []os.FileInfo) bool { + return slices.ContainsFunc(dirs, func(dir os.FileInfo) bool { + return os.SameFile(info, dir) + }) +} + +// below reports whether rel is dir or lies under it, going by the names. +func below(rel, dir string) bool { + return rel == dir || strings.HasPrefix(rel, dir+"/") } // relativeTo expresses rel, which is base or lies below it, relative to base. diff --git a/internal/app/fsutil/confine_test.go b/internal/app/fsutil/confine_test.go index 9110968..b287889 100644 --- a/internal/app/fsutil/confine_test.go +++ b/internal/app/fsutil/confine_test.go @@ -408,30 +408,157 @@ func TestConfiner_IsServerDir(t *testing.T) { assert.False(t, NewConfiner(workDir, WithRoot("servers/a")).IsServerDir(stat("servers/a"))) } -func TestLeadingLen(t *testing.T) { +// The game server directories are the ones on disk when the question is asked. +// One that was replaced since the Confiner was made, or since it was last +// asked, is known by its replacement, and the directory that used to stand +// there is a boundary no more. +func TestConfiner_IsServerDir_FollowsTheDirectoryOnDisk(t *testing.T) { t.Parallel() + workDir := confineTree(t) + serverDir := filepath.Join(workDir, "servers", "b") + + confiner := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})) + + former, err := os.Stat(serverDir) + require.NoError(t, err) + require.True(t, confiner.IsServerDir(former)) + + // The directory is put aside rather than removed: a removed one could hand + // its identity on to the directory created next. + require.NoError(t, os.Rename(serverDir, serverDir+".old")) + require.NoError(t, os.Mkdir(serverDir, 0o755)) + + replacement, err := os.Stat(serverDir) + require.NoError(t, err) + require.False(t, os.SameFile(former, replacement)) + + assert.True(t, confiner.IsServerDir(replacement), "the directory now standing there is the boundary") + assert.False(t, confiner.IsServerDir(former), "the directory put aside is not") + + require.NoError(t, os.Remove(serverDir)) + + assert.False(t, confiner.IsServerDir(replacement), "a game server directory that is gone confines nothing") +} + +func TestConfiner_Resolve_InServerDir(t *testing.T) { + t.Parallel() + + known := serverDirs{"servers/a", "servers/b"} + tests := []struct { - rel string - dir string - want string + name string + serverDirs ServerDirLister + root string + path string + target Target + want bool }{ - {rel: "servers/a/sub/inner.txt", dir: "servers/a", want: "servers/a"}, - {rel: "servers/a", dir: "servers/a", want: "servers/a"}, - {rel: "servers/ab/other.txt", dir: "servers/a", want: "servers/ab"}, - {rel: "SERVERS/A/own.txt", dir: "servers/a", want: "SERVERS/A"}, - {rel: "servers/a/own.txt", dir: "servers", want: "servers"}, - {rel: "servers/a/nested/deep.md", dir: "servers/a/nested", want: "servers/a/nested"}, - {rel: "servers", dir: "servers/a", want: ""}, - {rel: "servers/a", dir: "servers/a/nested", want: ""}, - {rel: ".", dir: "servers", want: ""}, + {name: "path_below_a_server_dir", serverDirs: known, path: "servers/a/sub/inner.txt", want: true}, + {name: "server_dir_as_tree", serverDirs: known, path: "servers/a", target: TargetTree, want: true}, + {name: "server_dir_as_entry", serverDirs: known, path: "servers/a"}, + {name: "path_outside_every_server_dir", serverDirs: known, path: "steamcmd/steamcmd.sh"}, + {name: "directory_holding_the_server_dirs", serverDirs: known, path: "servers", target: TargetTree}, + {name: "server_dir_not_on_disk_yet", serverDirs: serverDirs{"servers/new"}, path: "servers/new/server.cfg"}, + {name: "request_root_the_daemon_does_not_know", root: "servers/a", path: "servers/a/own.txt"}, + { + name: "request_root_that_is_a_server_dir_as_entry", + serverDirs: known, root: "servers/a", path: "servers/a", + want: true, + }, + { + name: "request_root_inside_a_server_dir", + serverDirs: known, root: "servers/a/nested", path: "servers/a/nested/deep.md", + want: true, + }, + { + name: "request_root_enclosing_the_server_dirs", + serverDirs: known, root: "servers", path: "servers/ab/other.txt", + }, } for _, tt := range tests { - t.Run(tt.rel+"_"+tt.dir, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { t.Parallel() - assert.Equal(t, tt.want, tt.rel[:leadingLen(tt.rel, tt.dir)]) + confiner := NewConfiner(confineTree(t), WithServerDirs(tt.serverDirs), WithRoot(tt.root)) + + got, err := confiner.Resolve(tt.path, tt.target) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, tt.want, got.InServerDir) }) } } + +// A boundary is compared by the name it is found under and then opened by that +// name. The walk moves into the directory it opened only when that is the one +// it compared; a name that has come to lead elsewhere in between is refused. +func TestPlacer_CrossTakesTheDirectoryItCompared(t *testing.T) { + t.Parallel() + + newPlacer := func(t *testing.T, at string) (*placer, os.FileInfo) { + t.Helper() + + work, err := os.OpenRoot(confineTree(t)) + require.NoError(t, err) + + p := &placer{root: work, scope: ".", at: at} + t.Cleanup(func() { _ = p.root.Close() }) + + boundary, err := work.Stat("servers/a") + require.NoError(t, err) + + p.reqRoot = boundary + + return p, boundary + } + + t.Run("the_directory_compared", func(t *testing.T) { + t.Parallel() + + p, boundary := newPlacer(t, "servers/a") + + require.NoError(t, p.cross(boundary)) + + assert.Equal(t, "servers/a", p.scope) + assert.Equal(t, ".", p.at) + assert.True(t, p.inRoot) + + opened, err := p.root.Stat(".") + require.NoError(t, err) + assert.True(t, os.SameFile(boundary, opened)) + }) + + t.Run("another_directory_under_the_name", func(t *testing.T) { + t.Parallel() + + p, boundary := newPlacer(t, "servers/b") + work := p.root + + err := p.cross(boundary) + + require.Error(t, err) + assert.Contains(t, err.Error(), `confinement directory "servers/b" was replaced while it was being opened`) + + assert.Same(t, work, p.root, "the walk stays where it was") + assert.Equal(t, "servers/b", p.at) + assert.False(t, p.inRoot) + }) + + t.Run("a_directory_that_is_no_boundary", func(t *testing.T) { + t.Parallel() + + p, _ := newPlacer(t, "servers/b") + work := p.root + + other, err := work.Stat("servers/b") + require.NoError(t, err) + + require.NoError(t, p.cross(other)) + + assert.Same(t, work, p.root) + assert.Equal(t, "servers/b", p.at) + }) +} diff --git a/internal/app/fsutil/confine_unix_test.go b/internal/app/fsutil/confine_unix_test.go index d35c8e6..2bc4409 100644 --- a/internal/app/fsutil/confine_unix_test.go +++ b/internal/app/fsutil/confine_unix_test.go @@ -286,7 +286,8 @@ func TestConfiner_RequestRootKeepsTheServerDirBoundary(t *testing.T) { } // A game server directory reached under a name the daemon does not know it by -// is still that directory: the request is confined to it all the same. +// is still that directory: the request is confined to it all the same, and +// placed under the name the link leads to. func TestConfiner_ServerDirUnderAnotherName(t *testing.T) { t.Parallel() @@ -309,8 +310,9 @@ func TestConfiner_ServerDirUnderAnotherName(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { _ = got.Close() }) - assert.Equal(t, "servers/alias", got.Scope) + assert.Equal(t, "servers/a", got.Scope) assert.Equal(t, "servers-link/b/secret.cfg", got.Rel) + assert.True(t, got.InServerDir) _, err = got.Root.ReadFile(got.Rel) require.Error(t, err) @@ -342,7 +344,7 @@ func TestConfiner_ServerDirUnderAnotherName(t *testing.T) { tree, err := confiner.Resolve("servers/alias", TargetTree) require.NoError(t, err) t.Cleanup(func() { _ = tree.Close() }) - assert.Equal(t, "servers/alias", tree.Scope) + assert.Equal(t, "servers/a", tree.Scope) assert.Equal(t, ".", tree.Rel) }) @@ -353,7 +355,7 @@ func TestConfiner_ServerDirUnderAnotherName(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { _ = got.Close() }) - assert.Equal(t, "servers/alias", got.Scope) + assert.Equal(t, "servers/a", got.Scope) _, err = got.Root.Stat("servers-link/b/secret.cfg") require.Error(t, err) @@ -438,3 +440,325 @@ func TestConfiner_ServerDirSpelledInAnotherCase(t *testing.T) { require.ErrorIs(t, err, ErrPathOutsideConfinement) assert.Nil(t, rooted) } + +// A link to a game server directory need not stand next to it. Whatever depth +// it is at, the path through it is confined to the directory it leads to, so +// that a link the tenant keeps there cannot carry the request back out. +func TestConfiner_ServerDirBehindALinkAtAnotherDepth(t *testing.T) { + t.Parallel() + + newTree := func(t *testing.T) string { + t.Helper() + + workDir := confineTree(t) + plantLinks(t, workDir) + + require.NoError(t, os.Symlink("servers/a", filepath.Join(workDir, "shortcut"))) + require.NoError(t, os.MkdirAll(filepath.Join(workDir, "links", "deep"), 0o755)) + require.NoError(t, os.Symlink("../../servers/a", filepath.Join(workDir, "links", "deep", "current"))) + + return workDir + } + + known := WithServerDirs(serverDirs{"servers/a", "servers/b"}) + + for _, alias := range []string{"shortcut", "links/deep/current"} { + t.Run(alias, func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + escaping, err := confiner.Resolve(alias+"/servers-link/b/secret.cfg", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = escaping.Close() }) + + assert.Equal(t, "servers/a", escaping.Scope) + assert.Equal(t, "servers-link/b/secret.cfg", escaping.Rel) + assert.True(t, escaping.InServerDir) + + _, err = escaping.Root.ReadFile(escaping.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + + own, err := confiner.Resolve(alias+"/in-link/inner.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = own.Close() }) + + content, err := own.Root.ReadFile(own.Rel) + require.NoError(t, err) + assert.Equal(t, "inner", string(content)) + + byName, err := confiner.Resolve("servers/a/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = byName.Close() }) + + assert.True(t, own.SameRoot(byName)) + }) + } + + t.Run("the_link_itself", func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + entry, err := confiner.Resolve("shortcut", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = entry.Close() }) + + assert.Equal(t, ".", entry.Scope) + assert.Equal(t, "shortcut", entry.Rel) + assert.False(t, entry.InServerDir) + + tree, err := confiner.Resolve("shortcut", TargetTree) + require.NoError(t, err) + t.Cleanup(func() { _ = tree.Close() }) + + assert.Equal(t, "servers/a", tree.Scope) + assert.Equal(t, ".", tree.Rel) + assert.True(t, tree.InServerDir) + }) + + t.Run("it_is_inside_the_request_root_it_leads_to", func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + require.NoError(t, os.Symlink("servers/b", filepath.Join(workDir, "other"))) + + confiner := NewConfiner(workDir, WithRoot("servers/a")) + + got, err := confiner.Resolve("shortcut/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/a", got.Scope) + + _, err = got.Root.Stat("servers-link/b/secret.cfg") + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + + root, err := confiner.Resolve("shortcut", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = root.Close() }) + + assert.Equal(t, "servers/a", root.Scope) + assert.Equal(t, ".", root.Rel) + + outside, err := confiner.Resolve("other/secret.cfg", TargetEntry) + + require.ErrorIs(t, err, ErrPathOutsideConfinement) + assert.Nil(t, outside) + }) +} + +// A link can also lead into the middle of a game server directory, to a +// directory that is no boundary itself. The path through it is placed in the +// game server directory that directory lies in. +func TestConfiner_LinkIntoTheMiddleOfAServerDir(t *testing.T) { + t.Parallel() + + newTree := func(t *testing.T) string { + t.Helper() + + workDir := confineTree(t) + + require.NoError(t, os.Mkdir(filepath.Join(workDir, "shortcuts"), 0o755)) + require.NoError(t, os.Symlink("../servers/a/sub", filepath.Join(workDir, "shortcuts", "current"))) + require.NoError(t, os.Symlink("../../b/secret.cfg", filepath.Join(workDir, "servers", "a", "sub", "leak"))) + require.NoError(t, os.Symlink("../own.txt", filepath.Join(workDir, "servers", "a", "sub", "inside"))) + + return workDir + } + + known := WithServerDirs(serverDirs{"servers/a", "servers/b"}) + + t.Run("link_out_of_the_server_dir_is_refused", func(t *testing.T) { + t.Parallel() + + got, err := NewConfiner(newTree(t), known).Resolve("shortcuts/current/leak", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/a", got.Scope) + assert.Equal(t, "sub/leak", got.Rel) + assert.True(t, got.InServerDir) + + content, err := got.Root.ReadFile(got.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Empty(t, content) + }) + + t.Run("link_staying_inside_is_followed", func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + for name, want := range map[string]string{"inner.txt": "inner", "inside": "own"} { + got, err := confiner.Resolve("shortcuts/current/"+name, TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + content, err := got.Root.ReadFile(got.Rel) + require.NoError(t, err) + assert.Equal(t, want, string(content)) + } + }) + + t.Run("the_link_itself", func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + entry, err := confiner.Resolve("shortcuts/current", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = entry.Close() }) + + assert.Equal(t, ".", entry.Scope) + assert.Equal(t, "shortcuts/current", entry.Rel) + + tree, err := confiner.Resolve("shortcuts/current", TargetTree) + require.NoError(t, err) + t.Cleanup(func() { _ = tree.Close() }) + + assert.Equal(t, "servers/a", tree.Scope) + assert.Equal(t, "sub", tree.Rel) + + _, err = tree.Root.Stat(tree.Rel + "/leak") + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) + + t.Run("a_request_root_does_not_lift_the_boundary", func(t *testing.T) { + t.Parallel() + + got, err := NewConfiner(newTree(t), known, WithRoot("/")).Resolve("shortcuts/current/leak", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/a", got.Scope) + + _, err = got.Root.ReadFile(got.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) +} + +// The tenant can turn what a node-level link points at into a link of its own. +// The path is in the game server directory by then, and does not get out. +func TestConfiner_LinkLeavingTheServerDirItLeadsInto(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + link string + path string + target Target + }{ + {name: "leading_component", link: "servers/a/servers-link", path: "shortcut/b/secret.cfg"}, + {name: "tree", link: "servers/a/servers-link/b", path: "shortcut", target: TargetTree}, + {name: "through_the_node", link: "servers/a/node-link/steamcmd", path: "shortcut/steamcmd.sh"}, + {name: "back_out_by_dot_dot", link: "servers/a/sub/../../b", path: "shortcut/secret.cfg"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + plantLinks(t, workDir) + require.NoError(t, os.Symlink(tt.link, filepath.Join(workDir, "shortcut"))) + + _, statErr := os.Stat(filepath.Join(workDir, filepath.FromSlash(tt.path))) + require.NoError(t, statErr, "the path leads somewhere when nothing confines it") + + got, err := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})). + Resolve(tt.path, tt.target) + + require.Error(t, err) + assert.Contains(t, err.Error(), `failed to follow link "shortcut"`) + assert.Nil(t, got) + }) + } +} + +// Passing a game server directory by is not entering it: a link written as +// "servers/a/../b" leads to the neighbour without ever being inside "a". +func TestConfiner_LinkPassingAServerDirBy(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("servers/a/../b", filepath.Join(workDir, "shortcut"))) + + got, err := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a", "servers/b"})). + Resolve("shortcut/secret.cfg", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/b", got.Scope) + assert.Equal(t, "secret.cfg", got.Rel) +} + +// A link that crosses no boundary changes nothing about where the path +// belongs. Followed on the way, it is replaced by what it leads to; named as +// the target of the operation, it is left for the operation to deal with. +func TestConfiner_LinkAboveTheServerDirs(t *testing.T) { + t.Parallel() + + newTree := func(t *testing.T) string { + t.Helper() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("steamcmd", filepath.Join(workDir, "tools"))) + require.NoError(t, os.Symlink("absent", filepath.Join(workDir, "dangling"))) + + return workDir + } + + tests := []struct { + name string + path string + target Target + wantRel string + }{ + {name: "followed_on_the_way", path: "tools/steamcmd.sh", wantRel: "steamcmd/steamcmd.sh"}, + {name: "named_as_an_entry", path: "tools", wantRel: "tools"}, + {name: "named_as_a_tree", path: "tools", target: TargetTree, wantRel: "tools"}, + {name: "dangling_on_the_way", path: "dangling/new.txt", wantRel: "dangling/new.txt"}, + {name: "missing_on_the_way", path: "fresh/dir/new.txt", wantRel: "fresh/dir/new.txt"}, + {name: "file_on_the_way", path: "steamcmd/steamcmd.sh/x", wantRel: "steamcmd/steamcmd.sh/x"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := NewConfiner(newTree(t), WithServerDirs(serverDirs{"servers/a", "servers/b"})). + Resolve(tt.path, tt.target) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, ".", got.Scope) + assert.Equal(t, tt.wantRel, got.Rel) + assert.False(t, got.InServerDir) + }) + } +} + +// A link chain that never ends is nothing os.Root follows, so the walk does +// not either: the path is left as it is, for the operation to fail on. +func TestConfiner_LinkLoop(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("pong", filepath.Join(workDir, "ping"))) + require.NoError(t, os.Symlink("ping", filepath.Join(workDir, "pong"))) + + got, err := NewConfiner(workDir, WithServerDirs(serverDirs{"servers/a"})).Resolve("ping/file.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "ping/file.txt", got.Rel) + + _, err = got.Root.Stat(got.Rel) + require.Error(t, err) +} diff --git a/internal/app/fsutil/copy.go b/internal/app/fsutil/copy.go index 7fea564..9054bad 100644 --- a/internal/app/fsutil/copy.go +++ b/internal/app/fsutil/copy.go @@ -36,8 +36,9 @@ type CopyOptions struct { // it keeps finding, and copying, what it has just written. var ErrCopyIntoItself = errors.New("cannot copy a directory into itself") -// ErrCopySameFile is returned when the source and the destination of a copy -// are one file. Opening the destination for writing would empty the source. +// ErrCopySameFile is returned when a file would be copied onto itself: its +// destination is the same file under this or another name. Emptying the +// destination to write it would empty the source. var ErrCopySameFile = errors.New("source and destination are the same file") // CopyInRoot copies src to dst where both are paths relative to the same root. @@ -49,8 +50,8 @@ func CopyInRoot(root *os.Root, src, dst string, opts CopyOptions) error { // existing destination and regular files overwrite an existing one, matching // the default behaviour of the recursive-copy library this package replaced. // -// A destination that is the source, or lies inside it, is refused with -// ErrCopyIntoItself or ErrCopySameFile. +// A directory is not copied into itself, and no file onto itself: the copy +// fails with ErrCopyIntoItself or ErrCopySameFile. func CopyTree(srcRoot *os.Root, src string, dstRoot *os.Root, dst string, opts CopyOptions) error { info, err := srcRoot.Lstat(src) if err != nil { @@ -74,33 +75,29 @@ func CopyTree(srcRoot *os.Root, src string, dstRoot *os.Root, dst string, opts C return err } -// refuseOverlap rejects, before anything is written, a copy whose destination -// is the source or one of the directories the destination is created in. The -// two are compared as files, not by name: they are named through different -// roots, and one directory can be spelled in more than one way. +// refuseOverlap rejects, before anything is written, the copy of a directory +// to itself or to one of the directories its destination is created in. The +// two are compared as directories, not by name: they are named through +// different roots, and one directory can be spelled in more than one way. // // A destination whose path leads into the source from outside of dstRoot, or // through a link, is not seen from here; copier.dir stops that copy as soon as -// it reaches the destination. +// it reaches the destination. A file is compared with its destination where it +// is written, see copier.file. func refuseOverlap(src fs.FileInfo, dstRoot *os.Root, dst string) error { - switch { - case src.IsDir(): - for dir := dst; ; dir = path.Dir(dir) { - if info, err := dstRoot.Stat(dir); err == nil && os.SameFile(src, info) { - return ErrCopyIntoItself - } - - if dir == "." || dir == "/" { - return nil - } + if !src.IsDir() { + return nil + } + + for dir := dst; ; dir = path.Dir(dir) { + if info, err := dstRoot.Stat(dir); err == nil && os.SameFile(src, info) { + return ErrCopyIntoItself } - case src.Mode().IsRegular(): - if info, err := dstRoot.Stat(dst); err == nil && os.SameFile(src, info) { - return ErrCopySameFile + + if dir == "." || dir == "/" { + return nil } } - - return nil } // Copy copies absolute src to absolute dst. It is a convenience for trusted, @@ -237,11 +234,20 @@ func (c *copier) file(src, dst string, info fs.FileInfo) error { perm := (info.Mode() | c.opts.AddPermission).Perm() - dstFile, err := c.dstRoot.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) + // The destination is opened as it stands and emptied only once it is known + // to be another file. Its name says nothing about that: a link in the + // destination tree, a link the source was reached through or a second name + // of the same file all lead back to what is being read. + dstFile, err := c.dstRoot.OpenFile(dst, os.O_WRONLY|os.O_CREATE, perm) if err != nil { return errors.Wrap(err, "failed to create destination file") } + if err := emptyUnlessSame(srcFile, dstFile); err != nil { + _ = dstFile.Close() + return errors.WithMessagef(err, "failed to copy %q to %q", src, dst) + } + if _, err := io.Copy(dstFile, srcFile); err != nil { _ = dstFile.Close() return errors.Wrap(err, "failed to copy file contents") @@ -260,6 +266,36 @@ func (c *copier) file(src, dst string, info fs.FileInfo) error { return nil } +// emptyUnlessSame truncates dst, unless it is the file src reads from. The two +// are compared as they were opened, so neither can become another file between +// the comparison and the write. +func emptyUnlessSame(src, dst *os.File) error { + srcInfo, err := src.Stat() + if err != nil { + return errors.Wrap(err, "failed to stat source file") + } + + dstInfo, err := dst.Stat() + if err != nil { + return errors.Wrap(err, "failed to stat destination file") + } + + if os.SameFile(srcInfo, dstInfo) { + return ErrCopySameFile + } + + // Only a regular file has a length to cut, as with O_TRUNC. + if !dstInfo.Mode().IsRegular() { + return nil + } + + if err := dst.Truncate(0); err != nil { + return errors.Wrap(err, "failed to truncate destination file") + } + + return nil +} + func (c *copier) symlink(src, dst string) error { switch c.opts.Symlink { case SymlinkSkip: diff --git a/internal/app/fsutil/copy_test.go b/internal/app/fsutil/copy_test.go index bf5cca9..0375eca 100644 --- a/internal/app/fsutil/copy_test.go +++ b/internal/app/fsutil/copy_test.go @@ -222,6 +222,43 @@ func TestCopyTree_FileOntoItself(t *testing.T) { require.NoError(t, CopyTree(root, "servers/a/own.txt", root, "servers/a/own-copy.txt", CopyOptions{})) } +// A second name of the source is the source: writing through it would empty +// the file before a byte of it is read. +func TestCopyTree_FileOntoItsHardLink(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + own := filepath.Join(workDir, "servers", "a", "own.txt") + + if err := os.Link(own, filepath.Join(workDir, "servers", "a", "own-hard.txt")); err != nil { + t.Skipf("cannot create a hard link: %v", err) + } + + root := openTestRoot(t, workDir) + + err := CopyTree(root, "servers/a/own.txt", root, "servers/a/own-hard.txt", CopyOptions{}) + require.ErrorIs(t, err, ErrCopySameFile) + + content, err := os.ReadFile(own) + require.NoError(t, err) + assert.Equal(t, "own", string(content), "the source must not be emptied") +} + +// The destination is emptied once it is known to be another file, so what was +// in it does not outlast a shorter copy. +func TestCopyTree_FileOverALongerOne(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + root := openTestRoot(t, workDir) + + require.NoError(t, CopyTree(root, "servers/a/own.txt", root, "servers/b/secret.cfg", CopyOptions{})) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "b", "secret.cfg")) + require.NoError(t, err) + assert.Equal(t, "own", string(content)) +} + // treeFiles reads every regular file below dir, keyed by its slash-separated // path, and lists the directories, so that two snapshots compare as a whole. func treeFiles(t *testing.T, dir string) map[string]string { diff --git a/internal/app/fsutil/copy_unix_test.go b/internal/app/fsutil/copy_unix_test.go index 7a35826..c73df62 100644 --- a/internal/app/fsutil/copy_unix_test.go +++ b/internal/app/fsutil/copy_unix_test.go @@ -107,3 +107,71 @@ func TestCopyTree_FileOntoItselfThroughALink(t *testing.T) { require.NoError(t, err) assert.Equal(t, "own", string(content)) } + +// A link that is followed is read as the file it leads to. When that file is +// the destination, the copy has nothing to read once the destination is +// emptied: the source is told from the destination as it is opened, not by the +// name it was asked for. +func TestCopyTree_FileOntoItselfThroughAFollowedLink(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("own.txt", filepath.Join(workDir, "servers", "a", "own-link.txt"))) + + root := openTestRoot(t, workDir) + + err := CopyTree(root, "servers/a/own-link.txt", root, "servers/a/own.txt", CopyOptions{Symlink: SymlinkDeep}) + require.ErrorIs(t, err, ErrCopySameFile) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "a", "own.txt")) + require.NoError(t, err) + assert.Equal(t, "own", string(content), "the source must not be emptied") +} + +// A link standing in the destination tree leads the write back to the source +// file, whatever the copy does with links it finds in the source. +func TestCopyTree_FileOntoItselfThroughALinkInTheDestination(t *testing.T) { + t.Parallel() + + for name, opts := range map[string]CopyOptions{ + "shallow": {}, + "deep": {Symlink: SymlinkDeep}, + "skip": {Symlink: SymlinkSkip}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + mirror := filepath.Join(workDir, "servers", "a", "mirror") + + require.NoError(t, os.Mkdir(mirror, 0o755)) + require.NoError(t, os.Symlink("../sub/inner.txt", filepath.Join(mirror, "inner.txt"))) + + root := openTestRoot(t, workDir) + + err := CopyTree(root, "servers/a/sub", root, "servers/a/mirror", opts) + require.ErrorIs(t, err, ErrCopySameFile) + + content, err := os.ReadFile(filepath.Join(workDir, "servers", "a", "sub", "inner.txt")) + require.NoError(t, err) + assert.Equal(t, "inner", string(content), "the source must not be emptied") + }) + } +} + +// A followed link to the directory the copy is written to makes every file in +// it its own destination. +func TestCopyTree_DirectoryOntoItselfThroughAFollowedLink(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink("a", filepath.Join(workDir, "servers", "alias"))) + + before := treeFiles(t, workDir) + root := openTestRoot(t, workDir) + + err := CopyTree(root, "servers/alias", root, "servers/a", CopyOptions{Symlink: SymlinkDeep}) + + require.ErrorIs(t, err, ErrCopySameFile) + assert.Equal(t, before, treeFiles(t, workDir), "no file may be emptied") +} diff --git a/internal/app/grpc/file_confinement_unix_test.go b/internal/app/grpc/file_confinement_unix_test.go index 1177dfb..ed2abc0 100644 --- a/internal/app/grpc/file_confinement_unix_test.go +++ b/internal/app/grpc/file_confinement_unix_test.go @@ -948,3 +948,78 @@ func TestGRPCFileHandler_CopyIntoItselfIsRefused(t *testing.T) { } } } + +// A link the node keeps outside every game server directory can lead to one, +// or into the middle of one. A request that goes through it is in that game +// server directory all the same, whatever name it got there by, so the links +// the tenant keeps inside do not carry it on to a neighbour. +func TestGRPCFileHandler_ServerDirBehindANodeLink(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + newHandler := func(t *testing.T) *GRPCFileHandler { + t.Helper() + + workDir := tenantWorkDir(t) + + require.NoError(t, os.Symlink("servers/a", filepath.Join(workDir, "shortcut"))) + require.NoError(t, os.Mkdir(filepath.Join(workDir, "shortcuts"), 0o755)) + require.NoError(t, os.Symlink("../servers/a/cstrike", filepath.Join(workDir, "shortcuts", "current"))) + require.NoError(t, os.Symlink( + "../../b/cstrike/server.cfg", filepath.Join(workDir, "servers", "a", "cstrike", "leak"), + )) + + return NewGRPCFileHandler(workDir, fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/b"})) + } + + for _, p := range []string{ + "shortcut/servers-link/b/cstrike/server.cfg", + "shortcut/file-link", + "shortcut/node-link/steamcmd/steamcmd.sh", + "shortcuts/current/leak", + } { + t.Run("refused/"+p, func(t *testing.T) { + t.Parallel() + + resp, err := newHandler(t).HandleFileRead(ctx, "r", &pb.FileReadRequest{Path: p}) + require.NoError(t, err) + + assert.False(t, resp.GetSuccess()) + assert.Contains(t, resp.GetError(), "path escapes from parent") + assert.Empty(t, resp.GetContent()) + }) + } + + for p, want := range map[string]string{ + "shortcut/own.txt": "own", + "shortcut/in-link/server.cfg": "hostname a", + "shortcuts/current/server.cfg": "hostname a", + "shortcuts/current/maps/de.bsp": "map", + } { + t.Run("own/"+p, func(t *testing.T) { + t.Parallel() + + resp, err := newHandler(t).HandleFileRead(ctx, "r", &pb.FileReadRequest{Path: p}) + require.NoError(t, err) + + require.True(t, resp.GetSuccess(), resp.GetError()) + assert.Equal(t, want, string(resp.GetContent())) + }) + } + + t.Run("listing_shows_the_directory_the_link_leads_to", func(t *testing.T) { + t.Parallel() + + resp, err := newHandler(t).HandleFileList(ctx, "l", &pb.FileListRequest{Path: "shortcuts/current"}) + require.NoError(t, err) + require.True(t, resp.GetSuccess(), resp.GetError()) + + names := make([]string, 0, len(resp.GetFiles())) + for _, file := range resp.GetFiles() { + names = append(names, file.GetName()) + } + + assert.ElementsMatch(t, []string{"server.cfg", "maps", "leak"}, names) + }) +} From bed2a0340e544af3fb96e3ec2b701bb36b1171b7 Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 17 Nov 2026 21:47:23 +0100 Subject: [PATCH 4/7] review fixes --- internal/app/archive/confine_unix_test.go | 86 ++++++ internal/app/archive/create.go | 49 ++-- internal/app/fsutil/confine.go | 306 +++++++++++++++++----- internal/app/fsutil/confine_test.go | 66 ++++- internal/app/fsutil/confine_unix_test.go | 255 +++++++++++++++++- 5 files changed, 651 insertions(+), 111 deletions(-) diff --git a/internal/app/archive/confine_unix_test.go b/internal/app/archive/confine_unix_test.go index 21c957b..c055188 100644 --- a/internal/app/archive/confine_unix_test.go +++ b/internal/app/archive/confine_unix_test.go @@ -772,6 +772,92 @@ func TestCreate_NodeLinkIntoTheMiddleOfAServer(t *testing.T) { }) } +// A game server directory can hold another. Each is a boundary of its own for +// whatever is packed: a link the nested tenant keeps does not reach the files +// of the outer server, whichever directory the request started from. +func TestCreate_NestedServerDir(t *testing.T) { + t.Parallel() + + opts := []fsutil.ConfineOption{ + fsutil.WithServerDirs(knownServerDirs{"servers/a", "servers/a/child", "servers/b"}), + } + + // newTree leaves server "a" with the link that stays inside it and puts + // server "child" into its directory. + newTree := func(t *testing.T) string { + t.Helper() + + workDir := tenantWorkDir(t) + for _, link := range []string{"servers-link", "node-link", "file-link"} { + require.NoError(t, os.Remove(filepath.Join(workDir, "servers", "a", link))) + } + + writeTree(t, workDir, map[string]string{"servers/a/child/data.txt": "child"}) + require.NoError(t, os.Symlink("data.txt", filepath.Join(workDir, "servers", "a", "child", "inside"))) + require.NoError(t, os.Symlink("child", filepath.Join(workDir, "servers", "a", "jump"))) + + return workDir + } + + requests := map[string]*pb.CreateArchiveParams{ + "nested_dir_named_from_the_work_dir": {BasePath: ".", Sources: []string{"servers/a/child"}}, + "nested_dir_named_from_the_outer_dir": {BasePath: "servers/a", Sources: []string{"child"}}, + "nested_dir_as_the_base": {BasePath: "servers/a/child", Sources: []string{"."}}, + "link_of_the_outer_dir_to_the_nested": {BasePath: "servers/a", Sources: []string{"jump"}}, + "outer_dir": {BasePath: "servers/a", Sources: []string{"."}}, + "directory_holding_the_servers": {BasePath: ".", Sources: []string{"servers"}}, + } + + for name, params := range requests { + t.Run("link_into_the_outer_dir_is_refused/"+name, func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + require.NoError(t, os.Symlink("../own.txt", filepath.Join(workDir, "servers", "a", "child", "leak"))) + + res, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: params.GetBasePath(), + Sources: params.GetSources(), + FollowSymlinks: true, + }, nil, opts...) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Nil(t, res) + + _, statErr := os.Lstat(filepath.Join(workDir, "backups", "node.zip")) + assert.ErrorIs(t, statErr, os.ErrNotExist, "a refused operation leaves no archive behind") + }) + + t.Run("links_staying_inside_the_nested_dir_are_followed/"+name, func(t *testing.T) { + t.Parallel() + + workDir := newTree(t) + + _, err := Create(context.Background(), workDir, &pb.CreateArchiveParams{ + ArchivePath: "backups/node.zip", + BasePath: params.GetBasePath(), + Sources: params.GetSources(), + FollowSymlinks: true, + }, nil, opts...) + require.NoError(t, err) + + contents := zipContents(t, filepath.Join(workDir, "backups", "node.zip")) + + followed := 0 + + for _, body := range contents { + if body == "child" { + followed++ + } + } + + assert.GreaterOrEqual(t, followed, 2, "data.txt and the link to it: %v", contents) + }) + } +} + // A walk lasts, and a game server directory can be removed and created again // while it does. The directory the walk then enters under that name confines // what is read below it, however long ago the walk first looked. diff --git a/internal/app/archive/create.go b/internal/app/archive/create.go index ccb2142..658fc92 100644 --- a/internal/app/archive/create.go +++ b/internal/app/archive/create.go @@ -215,10 +215,12 @@ type walkLimits struct { // Every source is placed by the confiner on its own, and the walk keeps to the // same boundary as it goes: a game server directory it enters from above is // read through a root opened at it, and a link it follows from above is read -// where the link ends, in the game server directory that place lies in. A tree -// packed for the node is thus confined the way a tree packed for one game -// server is: os.Root refuses a link leading out of the game server directory -// it stands in, whichever directory the request started from. +// where the link ends, in the game server directory that place lies in. Above +// is the work directory as much as a game server directory that holds another +// one. A tree packed for the node, or for a game server with others inside it, +// is thus confined the way a tree packed for a single game server is: os.Root +// refuses a link leading out of the game server directory it stands in, +// whichever directory the request started from. type sourceWalker struct { ctx context.Context confiner *fsutil.Confiner @@ -233,9 +235,9 @@ type sourceScope struct { dir os.FileInfo // path is where root stands, relative to the work directory. path string - // confined is set for a root standing in a game server directory. Nothing - // read through it leads out of that directory, so the walk looks for no - // further boundary below it. + // confined is set for a root standing in a game server directory that + // holds no other one. Nothing read through it leads out of that directory, + // so the walk looks for no further boundary below it. confined bool // owned roots are opened by the walker and closed with it. owned bool @@ -314,7 +316,7 @@ func (w *sourceWalker) adopt(placed *fsutil.Confined, owned bool) (*sourceScope, _ = placed.Root.Close() } - known.confined = known.confined || placed.InServerDir + known.confined = known.confined || placed.Innermost return known, nil } @@ -323,7 +325,7 @@ func (w *sourceWalker) adopt(placed *fsutil.Confined, owned bool) (*sourceScope, root: placed.Root, dir: dir, path: placed.Scope, - confined: placed.InServerDir, + confined: placed.Innermost, owned: owned, } @@ -432,12 +434,12 @@ func (w *sourceWalker) walk(scope *sourceScope, rel, name string, symlinkDepth i } } -// cross returns where to go on reading what the followed link rel of scope -// leads to, when that lies behind a boundary: the scope of the game server -// directory the link ends in and the path there. A link that crosses no -// boundary is read through the root it stands in, and nothing is returned. +// cross returns where to go on reading rel of scope, when that lies behind a +// boundary: the scope of the game server directory rel is, or the followed +// link rel ends in, and the path there. What crosses no boundary is read +// through the root it stands in, and nothing is returned. // -// The root of scope would follow the link wherever it leads below it, into the +// The root of scope would follow a link wherever it leads below it, into the // middle of a game server directory as well, and the links the tenant keeps // there would then be followed through that root too, out of the game server // directory again. @@ -506,23 +508,14 @@ func (w *sourceWalker) enter(scope *sourceScope, rel string, info os.FileInfo) ( return scope, rel, nil } - if known := w.scopeOf(info); known != nil { - known.confined = true - - return known, ".", nil - } - - dir := path.Join(scope.path, rel) - - inner, err := scope.root.OpenRoot(rel) + into, intoRel, err := w.cross(scope, rel) if err != nil { - return nil, "", errors.Wrapf(err, "failed to open game server directory %q", dir) + return nil, "", errors.WithMessagef(err, "failed to enter game server directory %q", path.Join(scope.path, rel)) } - into, err := w.adopt(&fsutil.Confined{Root: inner, Rel: ".", Scope: dir, InServerDir: true}, true) - if err != nil { - return nil, "", err + if into == nil { + return scope, rel, nil } - return into, ".", nil + return into, intoRel, nil } diff --git a/internal/app/fsutil/confine.go b/internal/app/fsutil/confine.go index e78f3e3..26b84dc 100644 --- a/internal/app/fsutil/confine.go +++ b/internal/app/fsutil/confine.go @@ -93,23 +93,29 @@ func WithRoot(root string) ConfineOption { // name, through a link standing anywhere above it, or through a link that // leads into the middle of it. A path that does not spell a game server // directory out is therefore walked down from the work directory one component -// at a time. Every directory on the way is compared with the boundaries as -// they are on disk at that moment, and every link is replaced by what it leads -// to, so the path ends up in the directory it really lies in. A boundary found -// this way is compared as it was opened: the directory the request goes on in -// is the one that was checked, whatever its name leads to a moment later. +// at a time. Every directory on the way is compared with what the names of the +// boundaries lead to, and every link is replaced by what it leads to, so the +// path ends up in the directory it really lies in. A boundary found this way +// is compared as it was opened: the directory the request goes on in is the +// one that was checked, whatever its name leads to a moment later. What the +// names lead to is looked up before the walk and once more after it. A game +// server directory removed and made anew in between is a boundary the walk +// could not tell, so the path is placed again. // // A path that does spell a game server directory the way the daemon knows it // is placed by that spelling alone, without a lookup, and os.Root keeps the -// rest of it inside. The walk would add nothing there unless game server -// directories are nested in one another and the path reaches a second one of -// them under another name. +// rest of it inside. That is enough as long as no other game server directory +// lies inside the one the path spells: the tenant of the outer one can lead to +// it under any name, so such a path is walked like the others. Whether one +// game server directory lies inside another is taken from the names the daemon +// knows them by. One it knows only by a name that leads into another through a +// link is not found to be nested. // // Resolve places the path a request names, and nothing below it. An operation -// that walks a tree from above the game server directories, as a request -// acting for the node rather than for one server can, crosses into them -// through the root it started with unless it asks IsServerDir about the -// directories it enters and Resolve about the links it follows. +// that goes on from there by itself, as packing a tree does, crosses into the +// game server directories below through the root it started with, unless that +// root is Innermost, or it asks IsServerDir about the directories it enters +// and Resolve about the links it follows. type Confiner struct { workDir string serverDirs ServerDirLister @@ -135,9 +141,12 @@ type Confined struct { // Scope is the directory Root is opened at, relative to the work directory // ("." for the work directory itself). Scope string - // InServerDir is set when Root stands at a game server directory or below - // one. Whatever is reached through such a root stays in that directory. - InServerDir bool + // Innermost is set when Root stands in a game server directory that holds + // no other one, going by the names the daemon knows them by. Whatever is + // reached through such a root stays in the game server directory it + // belongs to. Below any other root a game server directory may lie, with a + // boundary of its own. + Innermost bool } func (c *Confined) Close() error { @@ -166,10 +175,10 @@ func (c *Confined) SameRoot(other *Confined) bool { // that starts above the game server directories uses it to notice the ones it // enters, which no request path names. // -// The game server directories are looked up on every call. A walk lasts long -// enough for one of them to be removed and created again, and the directory -// found under its name then is not the one that stood there when the walk -// began. +// The game server directories are looked up on every call, after info was +// taken. A walk lasts long enough for one of them to be removed and created +// again, and the directory found under its name then is not the one that stood +// there when the walk began. func (c *Confiner) IsServerDir(info os.FileInfo) bool { names := c.serverNames() if len(names) == 0 || !info.IsDir() { @@ -182,7 +191,11 @@ func (c *Confiner) IsServerDir(info os.FileInfo) bool { } defer work.Close() - return isOneOf(info, onDisk(work, names)) + return slices.ContainsFunc(names, func(name string) bool { + dir := dirAt(work, name) + + return dir != nil && os.SameFile(info, dir) + }) } // Resolve places a caller-supplied path. See Confiner for the model. @@ -203,10 +216,10 @@ func (c *Confiner) Resolve(p string, target Target) (*Confined, error) { } if named, settled := b.named(rel, target); settled { - return openNamed(work, rel, named) + return b.openNamed(work, rel, named) } - return walk(work, b, rel, target) + return b.walk(work, rel, target, b.onDisk) } // bounds are the directories one request is confined by, spelled the way the @@ -262,9 +275,47 @@ type boundary struct { server bool } +// holds reports whether the daemon knows a game server directory by a name +// below dir. Letter case is not told apart, since the volume may not tell it +// apart either: two directories wrongly taken for nested cost a lookup, two +// wrongly taken for apart cost the boundary. +func (b bounds) holds(dir string) bool { + if dir == "." { + return len(b.servers) > 0 + } + + return slices.ContainsFunc(b.servers, func(name string) bool { + return belowFold(name, dir) + }) +} + +// belowFold reports whether name lies under dir, going by the names with the +// letter case folded. +func belowFold(name, dir string) bool { + for { + outer, dirRest, dirGoesOn := strings.Cut(dir, "/") + inner, nameRest, nameGoesOn := strings.Cut(name, "/") + + if !strings.EqualFold(outer, inner) { + return false + } + + if !dirGoesOn { + return nameGoesOn + } + + if !nameGoesOn { + return false + } + + dir, name = dirRest, nameRest + } +} + // named returns the boundaries rel spells out, outermost first, and whether // they settle where rel belongs: it names a game server directory, if the -// daemon knows any, and lies in the request root, if the request has one. +// daemon knows any, with no other one inside it, and lies in the request root, +// if the request has one. func (b bounds) named(rel string, target Target) ([]boundary, bool) { var found []boundary @@ -294,13 +345,25 @@ func (b bounds) named(rel string, target Target) ([]boundary, bool) { found = slices.CompactFunc(found, func(x, y boundary) bool { return x.end == y.end }) - return found, inRoot && inServer + if !inRoot || !inServer { + return nil, false + } + + // A game server directory inside the innermost one named is reached under + // whatever name the tenant of the outer one gives it. The spelling of rel + // does not show whether it passes that way. + if len(found) > 0 && b.holds(rel[:found[len(found)-1].end]) { + return nil, false + } + + return found, true } // openNamed opens the boundaries rel spells out, each from inside the one // before it. -func openNamed(work *os.Root, rel string, named []boundary) (*Confined, error) { +func (b bounds) openNamed(work *os.Root, rel string, named []boundary) (*Confined, error) { placed := &Confined{Root: work, Scope: "."} + inServer := false for _, bound := range named { dir := rel[:bound.end] @@ -322,10 +385,13 @@ func openNamed(work *os.Root, rel string, named []boundary) (*Confined, error) { _ = placed.Root.Close() placed.Root, placed.Scope = next, dir - placed.InServerDir = placed.InServerDir || bound.server + inServer = inServer || bound.server } placed.Rel = relativeTo(rel, placed.Scope) + // The boundary reached is not the innermost one named when that one is + // not on disk, and the one enclosing it can hold more. + placed.Innermost = inServer && !b.holds(placed.Scope) return placed, nil } @@ -335,14 +401,115 @@ func openNamed(work *os.Root, rel string, named []boundary) (*Confined, error) { // that keeps changing underneath the walk. const maxLinkHops = 64 +// maxPlacements bounds how often one path is placed anew because the +// boundaries changed underneath the walk. +const maxPlacements = 4 + +// landmarks are the boundaries as they are on disk at one moment: what the +// names the daemon knows them by lead to. A name that leads to no directory +// has nil for it, and confines nothing. +type landmarks struct { + // servers has an entry for every name in bounds.servers, in that order. + servers []os.FileInfo + root os.FileInfo +} + +func (b bounds) onDisk(work *os.Root) landmarks { + found := landmarks{servers: make([]os.FileInfo, len(b.servers))} + + for i, name := range b.servers { + found.servers[i] = dirAt(work, name) + } + + if b.root != "" { + found.root = dirAt(work, b.root) + } + + return found +} + +func (l landmarks) hasServers() bool { + return slices.ContainsFunc(l.servers, func(dir os.FileInfo) bool { return dir != nil }) +} + +// same reports whether every name leads to the directory it leads to in other. +func (l landmarks) same(other landmarks) bool { + return sameDir(l.root, other.root) && slices.EqualFunc(l.servers, other.servers, sameDir) +} + +func sameDir(x, y os.FileInfo) bool { + if x == nil || y == nil { + return x == nil && y == nil + } + + return os.SameFile(x, y) +} + +func dirAt(work *os.Root, name string) os.FileInfo { + if info, err := work.Stat(name); err == nil && info.IsDir() { + return info + } + + return nil +} + +// walk places a path that does not spell its boundaries out, and takes work +// over. look describes the boundaries on disk. +// +// The walk tells a boundary by what look found before it began. A directory +// made under the name of a boundary since then is passed like any other, and a +// link in it is followed through the root enclosing it. The names are therefore +// looked up again once the path is placed, and the placement stands only if +// they still lead where they did: every directory the walk passed was then +// compared with what the names led to after the walk had seen it. +func (b bounds) walk(work *os.Root, rel string, target Target, look func(*os.Root) landmarks) (*Confined, error) { + if rel == "." { + placed, err := b.place(work, landmarks{}, rel, target) + if err != nil { + _ = work.Close() + } + + return placed, err + } + + seen := look(work) + + for range maxPlacements { + placed, err := b.place(work, seen, rel, target) + + now := look(work) + if seen.same(now) { + if err != nil || placed.Root != work { + _ = work.Close() + } + + return placed, err + } + + if err == nil && placed.Root != work { + _ = placed.Root.Close() + } + + seen = now + } + + _ = work.Close() + + return nil, errors.Errorf( + "failed to place %q: the game server directories on its way kept changing, %d attempts made", + rel, maxPlacements, + ) +} + // placer walks a request path down from the work directory and moves into // every boundary the path passes. type placer struct { - // servers and reqRoot are the boundaries as they are on disk. reqRoot is - // nil when the request names no root or the root is not there. - servers []os.FileInfo - reqRoot os.FileInfo + bounds bounds + // seen is what the names of the boundaries led to before the walk began. + seen landmarks + // work is the root the walk starts in. It is left open whatever happens. + work *os.Root // root is the innermost boundary reached, opened at scope. root *os.Root scope string @@ -351,30 +518,26 @@ type placer struct { inRoot bool inServer bool - hops int + // nested is set while the daemon knows a game server directory by a name + // below the boundary the walk stands in. + nested bool + hops int } -// walk places a path that does not spell its boundaries out. -func walk(work *os.Root, b bounds, rel string, target Target) (*Confined, error) { - p := &placer{root: work, scope: ".", at: "."} +// place walks rel down from work, telling the boundaries by seen. The root of +// what it returns is work or one it opened; nothing else is left open. +func (b bounds) place(work *os.Root, seen landmarks, rel string, target Target) (*Confined, error) { + p := &placer{bounds: b, seen: seen, work: work, root: work, scope: ".", at: ".", nested: b.holds(".")} var names []string - if rel != "." { names = strings.Split(rel, "/") - p.servers = onDisk(work, b.servers) - - if b.root != "" { - if dirs := onDisk(work, []string{b.root}); len(dirs) > 0 { - p.reqRoot = dirs[0] - } - } } for i, name := range names { moved, err := p.step(name, i == len(names)-1, target) if err != nil { - _ = p.root.Close() + p.leave() return nil, err } @@ -389,12 +552,19 @@ func walk(work *os.Root, b bounds, rel string, target Target) (*Confined, error) // A request root that is spelled out but not on disk yet has nothing in it // to keep the request from, like any other boundary that is not there. if b.root != "" && !p.inRoot && !below(rel, b.root) { - _ = p.root.Close() + p.leave() return nil, ErrPathOutsideConfinement } - return &Confined{Root: p.root, Rel: p.at, Scope: p.scope, InServerDir: p.inServer}, nil + return &Confined{Root: p.root, Rel: p.at, Scope: p.scope, Innermost: p.inServer && !p.nested}, nil +} + +// leave closes the boundary the walk stands in. +func (p *placer) leave() { + if p.root != p.work { + _ = p.root.Close() + } } // step takes the walk one component of the request path further and reports @@ -402,7 +572,7 @@ func walk(work *os.Root, b bounds, rel string, target Target) (*Confined, error) // the request spells it, for os.Root to resolve from where the walk stands. func (p *placer) step(name string, last bool, target Target) (bool, error) { // No boundary is left to be found. - if len(p.servers) == 0 && (p.reqRoot == nil || p.inRoot) { + if !p.seen.hasServers() && (p.seen.root == nil || p.inRoot) { return false, nil } @@ -535,12 +705,12 @@ func (p *placer) tree(name string) (bool, error) { // entry of the directory the walk stands in. Only the request root is moved // into: named as an entry, it still is the directory the request is kept in. func (p *placer) entry(name string) (bool, error) { - if p.reqRoot == nil || p.inRoot { + if p.seen.root == nil || p.inRoot { return false, nil } info, err := p.root.Stat(path.Join(p.at, name)) - if err != nil || !os.SameFile(info, p.reqRoot) { + if err != nil || !os.SameFile(info, p.seen.root) { return false, nil } @@ -559,13 +729,26 @@ func (p *placer) entry(name string) (bool, error) { // cross moves the walk into the directory it stands at when that directory is // a boundary. info describes the directory as it was found by name. func (p *placer) cross(info os.FileInfo) error { - isRoot := p.reqRoot != nil && os.SameFile(info, p.reqRoot) - isServer := isOneOf(info, p.servers) + // One directory can be known by several names. + var known []string + + for i, dir := range p.seen.servers { + if dir != nil && os.SameFile(info, dir) { + known = append(known, p.bounds.servers[i]) + } + } + + isRoot := p.seen.root != nil && os.SameFile(info, p.seen.root) + isServer := len(known) > 0 if !isRoot && !isServer { return nil } + if isRoot { + known = append(known, p.bounds.root) + } + dir := path.Join(p.scope, p.at) inner, err := p.root.OpenRoot(p.at) @@ -589,35 +772,16 @@ func (p *placer) cross(info os.FileInfo) error { return errors.Errorf("confinement directory %q was replaced while it was being opened", dir) } - _ = p.root.Close() + p.leave() p.root, p.scope, p.at = inner, dir, "." p.inRoot = p.inRoot || isRoot p.inServer = p.inServer || isServer + p.nested = slices.ContainsFunc(known, p.bounds.holds) return nil } -// onDisk describes the directories the names lead to at this moment. A name -// that leads to none confines nothing. -func onDisk(work *os.Root, names []string) []os.FileInfo { - var dirs []os.FileInfo - - for _, name := range names { - if info, err := work.Stat(name); err == nil && info.IsDir() { - dirs = append(dirs, info) - } - } - - return dirs -} - -func isOneOf(info os.FileInfo, dirs []os.FileInfo) bool { - return slices.ContainsFunc(dirs, func(dir os.FileInfo) bool { - return os.SameFile(info, dir) - }) -} - // below reports whether rel is dir or lies under it, going by the names. func below(rel, dir string) bool { return rel == dir || strings.HasPrefix(rel, dir+"/") diff --git a/internal/app/fsutil/confine_test.go b/internal/app/fsutil/confine_test.go index b287889..bd08aa3 100644 --- a/internal/app/fsutil/confine_test.go +++ b/internal/app/fsutil/confine_test.go @@ -441,10 +441,11 @@ func TestConfiner_IsServerDir_FollowsTheDirectoryOnDisk(t *testing.T) { assert.False(t, confiner.IsServerDir(replacement), "a game server directory that is gone confines nothing") } -func TestConfiner_Resolve_InServerDir(t *testing.T) { +func TestConfiner_Resolve_Innermost(t *testing.T) { t.Parallel() known := serverDirs{"servers/a", "servers/b"} + nested := serverDirs{"servers/a", "servers/a/nested", "servers/b"} tests := []struct { name string @@ -475,6 +476,28 @@ func TestConfiner_Resolve_InServerDir(t *testing.T) { name: "request_root_enclosing_the_server_dirs", serverDirs: known, root: "servers", path: "servers/ab/other.txt", }, + {name: "server_dir_holding_another", serverDirs: nested, path: "servers/a/own.txt"}, + {name: "server_dir_holding_another_as_tree", serverDirs: nested, path: "servers/a", target: TargetTree}, + {name: "server_dir_held_by_another", serverDirs: nested, path: "servers/a/nested/deep.md", want: true}, + { + name: "server_dir_held_by_another_as_tree", + serverDirs: nested, path: "servers/a/nested", target: TargetTree, + want: true, + }, + {name: "server_dir_held_by_another_as_entry", serverDirs: nested, path: "servers/a/nested"}, + { + name: "server_dir_holding_one_known_in_another_letter_case", + serverDirs: serverDirs{"servers/a", "Servers/A/nested"}, path: "servers/a/own.txt", + }, + { + name: "request_root_not_on_disk_in_a_server_dir_holding_another", + serverDirs: nested, root: "servers/a/new", path: "servers/a/new/server.cfg", + }, + { + name: "request_root_in_a_server_dir_holding_another", + serverDirs: nested, root: "servers/a/sub", path: "servers/a/sub/inner.txt", + want: true, + }, } for _, tt := range tests { @@ -487,7 +510,7 @@ func TestConfiner_Resolve_InServerDir(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { _ = got.Close() }) - assert.Equal(t, tt.want, got.InServerDir) + assert.Equal(t, tt.want, got.Innermost) }) } } @@ -504,13 +527,23 @@ func TestPlacer_CrossTakesTheDirectoryItCompared(t *testing.T) { work, err := os.OpenRoot(confineTree(t)) require.NoError(t, err) - p := &placer{root: work, scope: ".", at: at} - t.Cleanup(func() { _ = p.root.Close() }) - boundary, err := work.Stat("servers/a") require.NoError(t, err) - p.reqRoot = boundary + p := &placer{ + bounds: bounds{root: "servers/a"}, + seen: landmarks{root: boundary}, + work: work, + root: work, + scope: ".", + at: at, + } + + t.Cleanup(func() { + p.leave() + + _ = work.Close() + }) return p, boundary } @@ -562,3 +595,24 @@ func TestPlacer_CrossTakesTheDirectoryItCompared(t *testing.T) { assert.Equal(t, "servers/b", p.at) }) } + +func TestBounds_Holds(t *testing.T) { + t.Parallel() + + b := bounds{servers: []string{"servers/a", "servers/a/nested", "Servers/B/inner", "servers/ab"}} + + for dir, want := range map[string]bool{ + ".": true, + "servers": true, + "servers/a": true, + "servers/a/nested": false, + "servers/a/sub": false, + "servers/b": true, + "servers/ab": false, + "steamcmd": false, + } { + assert.Equal(t, want, b.holds(dir), dir) + } + + assert.False(t, bounds{}.holds(".")) +} diff --git a/internal/app/fsutil/confine_unix_test.go b/internal/app/fsutil/confine_unix_test.go index 2bc4409..7a00701 100644 --- a/internal/app/fsutil/confine_unix_test.go +++ b/internal/app/fsutil/confine_unix_test.go @@ -3,6 +3,7 @@ package fsutil import ( + "fmt" "os" "path/filepath" "testing" @@ -312,7 +313,7 @@ func TestConfiner_ServerDirUnderAnotherName(t *testing.T) { assert.Equal(t, "servers/a", got.Scope) assert.Equal(t, "servers-link/b/secret.cfg", got.Rel) - assert.True(t, got.InServerDir) + assert.True(t, got.Innermost) _, err = got.Root.ReadFile(got.Rel) require.Error(t, err) @@ -474,7 +475,7 @@ func TestConfiner_ServerDirBehindALinkAtAnotherDepth(t *testing.T) { assert.Equal(t, "servers/a", escaping.Scope) assert.Equal(t, "servers-link/b/secret.cfg", escaping.Rel) - assert.True(t, escaping.InServerDir) + assert.True(t, escaping.Innermost) _, err = escaping.Root.ReadFile(escaping.Rel) require.Error(t, err) @@ -507,7 +508,7 @@ func TestConfiner_ServerDirBehindALinkAtAnotherDepth(t *testing.T) { assert.Equal(t, ".", entry.Scope) assert.Equal(t, "shortcut", entry.Rel) - assert.False(t, entry.InServerDir) + assert.False(t, entry.Innermost) tree, err := confiner.Resolve("shortcut", TargetTree) require.NoError(t, err) @@ -515,7 +516,7 @@ func TestConfiner_ServerDirBehindALinkAtAnotherDepth(t *testing.T) { assert.Equal(t, "servers/a", tree.Scope) assert.Equal(t, ".", tree.Rel) - assert.True(t, tree.InServerDir) + assert.True(t, tree.Innermost) }) t.Run("it_is_inside_the_request_root_it_leads_to", func(t *testing.T) { @@ -580,7 +581,7 @@ func TestConfiner_LinkIntoTheMiddleOfAServerDir(t *testing.T) { assert.Equal(t, "servers/a", got.Scope) assert.Equal(t, "sub/leak", got.Rel) - assert.True(t, got.InServerDir) + assert.True(t, got.Innermost) content, err := got.Root.ReadFile(got.Rel) require.Error(t, err) @@ -739,7 +740,7 @@ func TestConfiner_LinkAboveTheServerDirs(t *testing.T) { assert.Equal(t, ".", got.Scope) assert.Equal(t, tt.wantRel, got.Rel) - assert.False(t, got.InServerDir) + assert.False(t, got.Innermost) }) } } @@ -762,3 +763,245 @@ func TestConfiner_LinkLoop(t *testing.T) { _, err = got.Root.Stat(got.Rel) require.Error(t, err) } + +// A game server directory can hold another, and the outer tenant can link to +// the nested one. A path through that link is in the nested directory all the +// same, so a link the nested tenant keeps there does not lead back out into +// the outer one, although the path spells the outer directory by its name. +func TestConfiner_NestedServerDirBehindALink(t *testing.T) { + t.Parallel() + + newTree := func(t *testing.T) string { + t.Helper() + + workDir := confineTree(t) + outer := filepath.Join(workDir, "servers", "a") + + require.NoError(t, os.Symlink("nested", filepath.Join(outer, "jump"))) + require.NoError(t, os.Symlink("../nested", filepath.Join(outer, "sub", "hop"))) + require.NoError(t, os.Symlink("../own.txt", filepath.Join(outer, "nested", "leak"))) + require.NoError(t, os.Symlink("deep.md", filepath.Join(outer, "nested", "inside"))) + + return workDir + } + + known := WithServerDirs(serverDirs{"servers/a", "servers/a/nested", "servers/b"}) + + for _, alias := range []string{"servers/a/jump", "servers/a/sub/hop", "servers/a/nested"} { + t.Run("link_out_of_the_nested_dir_is_refused/"+alias, func(t *testing.T) { + t.Parallel() + + for name, opts := range map[string][]ConfineOption{ + "known_server_dirs": {known}, + "request_root_of_the_outer": {known, WithRoot("servers/a")}, + } { + got, err := NewConfiner(newTree(t), opts...).Resolve(alias+"/leak", TargetEntry) + require.NoError(t, err, name) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/a/nested", got.Scope, name) + assert.Equal(t, "leak", got.Rel, name) + + content, err := got.Root.ReadFile(got.Rel) + require.Error(t, err, name) + assert.Contains(t, err.Error(), "path escapes from parent", name) + assert.Empty(t, content, name) + } + }) + + t.Run("link_staying_inside_the_nested_dir_is_followed/"+alias, func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + for _, name := range []string{"deep.md", "inside"} { + got, err := confiner.Resolve(alias+"/"+name, TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + content, err := got.Root.ReadFile(got.Rel) + require.NoError(t, err) + assert.Equal(t, "deep", string(content)) + } + }) + } + + t.Run("the_outer_dir_keeps_its_own_files", func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + for name, want := range map[string]string{ + "servers/a/own.txt": "own", + "servers/a/sub/inner.txt": "inner", + } { + got, err := confiner.Resolve(name, TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = got.Close() }) + + assert.Equal(t, "servers/a", got.Scope) + + content, err := got.Root.ReadFile(got.Rel) + require.NoError(t, err) + assert.Equal(t, want, string(content)) + } + }) + + t.Run("the_link_itself_belongs_to_the_outer_dir", func(t *testing.T) { + t.Parallel() + + confiner := NewConfiner(newTree(t), known) + + entry, err := confiner.Resolve("servers/a/jump", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = entry.Close() }) + + assert.Equal(t, "servers/a", entry.Scope) + assert.Equal(t, "jump", entry.Rel) + + tree, err := confiner.Resolve("servers/a/jump", TargetTree) + require.NoError(t, err) + t.Cleanup(func() { _ = tree.Close() }) + + assert.Equal(t, "servers/a/nested", tree.Scope) + assert.Equal(t, ".", tree.Rel) + }) +} + +// A game server directory can be removed and made anew while a path is being +// placed. The walk tells the boundaries by what their names led to before it +// began: the directory standing there now is passed like any other, and the +// link in it is followed through the work directory into another game server. +// The path is placed again once the names are found to lead elsewhere. +func TestWalk_ServerDirReplacedWhileThePathIsPlaced(t *testing.T) { + t.Parallel() + + // replacing looks the boundaries up and, once it has done so for the first + // time, has server "a" replaced by a directory with a link out of it. + replacing := func(t *testing.T, workDir string, b bounds, looks *int) func(*os.Root) landmarks { + t.Helper() + + return func(work *os.Root) landmarks { + seen := b.onDisk(work) + + if *looks++; *looks == 1 { + serverDir := filepath.Join(workDir, "servers", "a") + + require.NoError(t, os.Rename(serverDir, filepath.Join(workDir, "removed-a"))) + require.NoError(t, os.Mkdir(serverDir, 0o755)) + require.NoError(t, os.Symlink("..", filepath.Join(serverDir, "servers-link"))) + require.NoError(t, os.WriteFile(filepath.Join(serverDir, "fresh.txt"), []byte("fresh"), 0o644)) + } + + return seen + } + } + + modes := map[string]bounds{ + "known_server_dirs": {servers: []string{"servers/a", "servers/b"}}, + "request_root": {root: "servers/a"}, + "both": {servers: []string{"servers/a", "servers/b"}, root: "servers/a"}, + } + + for name, b := range modes { + t.Run("link_in_the_new_dir_is_refused/"+name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + + work, err := os.OpenRoot(workDir) + require.NoError(t, err) + + looks := 0 + + placed, err := b.walk(work, "servers/a/servers-link/b/secret.cfg", TargetEntry, replacing(t, workDir, b, &looks)) + require.NoError(t, err) + t.Cleanup(func() { _ = placed.Close() }) + + assert.Equal(t, 3, looks, "before the walk, after it, and after the walk made anew") + assert.Equal(t, "servers/a", placed.Scope) + + content, err := placed.Root.ReadFile(placed.Rel) + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + assert.Empty(t, content) + }) + + t.Run("path_is_placed_in_the_new_dir/"+name, func(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + + work, err := os.OpenRoot(workDir) + require.NoError(t, err) + + looks := 0 + + placed, err := b.walk(work, "servers/a/fresh.txt", TargetEntry, replacing(t, workDir, b, &looks)) + require.NoError(t, err) + t.Cleanup(func() { _ = placed.Close() }) + + assert.Equal(t, 3, looks) + assert.Equal(t, "servers/a", placed.Scope) + assert.Equal(t, "fresh.txt", placed.Rel) + + content, err := placed.Root.ReadFile(placed.Rel) + require.NoError(t, err) + assert.Equal(t, "fresh", string(content)) + }) + } + + t.Run("boundaries_that_stay_are_looked_up_twice", func(t *testing.T) { + t.Parallel() + + b := modes["both"] + + work, err := os.OpenRoot(confineTree(t)) + require.NoError(t, err) + + looks := 0 + + placed, err := b.walk(work, "servers/a/own.txt", TargetEntry, func(work *os.Root) landmarks { + looks++ + + return b.onDisk(work) + }) + require.NoError(t, err) + t.Cleanup(func() { _ = placed.Close() }) + + assert.Equal(t, 2, looks) + assert.Equal(t, "servers/a", placed.Scope) + }) + + t.Run("boundaries_that_keep_changing_fail_the_request", func(t *testing.T) { + t.Parallel() + + b := modes["known_server_dirs"] + workDir := confineTree(t) + + work, err := os.OpenRoot(workDir) + require.NoError(t, err) + + looks := 0 + + placed, err := b.walk(work, "servers/a/own.txt", TargetEntry, func(work *os.Root) landmarks { + seen := b.onDisk(work) + looks++ + + serverDir := filepath.Join(workDir, "servers", "b") + + require.NoError(t, os.Rename(serverDir, filepath.Join(workDir, fmt.Sprintf("removed-b-%d", looks)))) + require.NoError(t, os.Mkdir(serverDir, 0o755)) + + return seen + }) + + require.Error(t, err) + assert.Contains(t, err.Error(), "kept changing") + assert.Nil(t, placed) + assert.Equal(t, maxPlacements+1, looks) + + _, err = work.Stat(".") + assert.ErrorIs(t, err, os.ErrClosed, "the work directory is not left open") + }) +} From c73d442edfb75c00aff16bd32464f7c5b1a237b4 Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 17 Nov 2026 22:04:29 +0100 Subject: [PATCH 5/7] bump dependencies --- go.mod | 86 ++++++++++++++--------------- go.sum | 172 ++++++++++++++++++++++++++++----------------------------- 2 files changed, 129 insertions(+), 129 deletions(-) diff --git a/go.mod b/go.mod index d9b5ee6..b8b7e74 100644 --- a/go.mod +++ b/go.mod @@ -12,56 +12,56 @@ require ( github.com/gameap/gameapctl v0.34.0 github.com/goccy/go-yaml v1.19.2 github.com/gopherclass/go-shellquote v0.0.0-20200814145606-fab22d094485 - github.com/hashicorp/go-getter v1.8.9 + github.com/hashicorp/go-getter v1.8.10 github.com/klauspost/compress v1.20.2 - github.com/moby/moby/api v1.56.0 - github.com/moby/moby/client v0.6.0 - github.com/nwaples/rardecode/v2 v2.4.1 + github.com/moby/moby/api v1.56.1 + github.com/moby/moby/client v0.6.2 + github.com/nwaples/rardecode/v2 v2.4.4 github.com/pkg/errors v0.9.1 github.com/rs/xid v1.6.0 - github.com/shirou/gopsutil/v4 v4.26.8 + github.com/shirou/gopsutil/v4 v4.26.10 github.com/sirupsen/logrus v1.10.2 github.com/stretchr/testify v1.12.1 github.com/ulikunitz/xz v0.5.17 github.com/urfave/cli/v2 v2.27.7 go.uber.org/mock v0.6.0 - golang.org/x/sync v0.23.0 - golang.org/x/sys v0.48.0 - google.golang.org/grpc v1.84.0 + golang.org/x/sync v0.25.0 + golang.org/x/sys v0.50.0 + google.golang.org/grpc v1.85.0 google.golang.org/protobuf v1.36.12 ) require ( - cel.dev/expr v0.25.2 // indirect + cel.dev/expr v0.25.3 // indirect cloud.google.com/go v0.123.0 // indirect - cloud.google.com/go/auth v0.23.2 // indirect + cloud.google.com/go/auth v0.23.3 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - cloud.google.com/go/compute/metadata v0.9.0 // indirect + cloud.google.com/go/compute/metadata v0.9.1 // indirect cloud.google.com/go/iam v1.12.0 // indirect cloud.google.com/go/monitoring v1.30.0 // indirect - cloud.google.com/go/storage v1.65.1 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0 // indirect + cloud.google.com/go/storage v1.68.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.57.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/andybalholm/brotli v1.2.7 // indirect - github.com/aws/aws-sdk-go-v2 v1.44.0 // indirect + github.com/aws/aws-sdk-go-v2 v1.47.1 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect - github.com/aws/aws-sdk-go-v2/config v1.32.40 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.19.39 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.40 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.40 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.40 // indirect - github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.41 // indirect + github.com/aws/aws-sdk-go-v2/config v1.33.6 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.20.6 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.10.0 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.40 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.41 // indirect - github.com/aws/aws-sdk-go-v2/service/s3 v1.108.0 // indirect - github.com/aws/aws-sdk-go-v2/service/signin v1.6.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.34.0 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.39.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.46.0 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect + github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 // indirect github.com/aws/smithy-go v1.28.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bodgit/plumbing v1.3.0 // indirect @@ -71,21 +71,21 @@ require ( github.com/containerd/errdefs/pkg v0.3.0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect github.com/distribution/reference v0.6.0 // indirect - github.com/docker/go-connections v0.7.0 // indirect + github.com/docker/go-connections v0.8.2 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect - github.com/ebitengine/purego v0.10.2 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect + github.com/ebitengine/purego v0.11.2 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be // indirect github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect github.com/go-jose/go-jose/v4 v4.1.4 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.6 // indirect - github.com/google/s2a-go v0.1.9 // indirect + github.com/google/s2a-go v0.1.10 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.20 // indirect - github.com/googleapis/gax-go/v2 v2.24.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.22 // indirect + github.com/googleapis/gax-go/v2 v2.24.1 // indirect github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.74 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-version v1.9.0 // indirect @@ -97,19 +97,19 @@ require ( github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pierrec/lz4/v4 v4.1.27 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect - github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shirou/gopsutil/v3 v3.24.5 // indirect github.com/shoenig/go-m1cpu v0.1.6 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spiffe/go-spiffe/v2 v2.8.1 // indirect github.com/stangelandcl/ppmd v0.1.1 // indirect - github.com/tklauser/go-sysconf v0.3.16 // indirect - github.com/tklauser/numcpus v0.11.0 // indirect + github.com/tklauser/go-sysconf v0.4.0 // indirect + github.com/tklauser/numcpus v0.12.0 // indirect github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.45.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect go.opentelemetry.io/otel v1.45.0 // indirect @@ -121,11 +121,11 @@ require ( go4.org v0.0.0-20260112195520-a5071408f32f // indirect golang.org/x/crypto v0.57.0 // indirect golang.org/x/net v0.60.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect + golang.org/x/oauth2 v0.37.0 // indirect golang.org/x/text v0.42.0 // indirect - golang.org/x/time v0.15.0 // indirect - google.golang.org/api v0.294.0 // indirect + golang.org/x/time v0.16.0 // indirect + google.golang.org/api v0.299.0 // indirect google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260715232425-e75dac1f907d // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect ) diff --git a/go.sum b/go.sum index c4b86f5..32098d6 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,13 @@ -cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= -cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= +cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -cloud.google.com/go/auth v0.23.2 h1:pxSCpfiji41hpzpPdMCftEUCezpgpqmmDdYiAjCKXxo= -cloud.google.com/go/auth v0.23.2/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0= +cloud.google.com/go/auth v0.23.3 h1:UMK+oBtuNGMCR/6i6mmySUItqjOazpJrbmZyhGbGBWo= +cloud.google.com/go/auth v0.23.3/go.mod h1:fClbry28fo7XkxhSeT6AQtAVAp6Jy0fW9N99PoPNPFM= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= -cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +cloud.google.com/go/compute/metadata v0.9.1 h1:CTE1OWBQ0vnF5uHwdFAQJvMQ0Fi/KRcqqKTo9V0F8Ik= +cloud.google.com/go/compute/metadata v0.9.1/go.mod h1:NtnlvB6X3t4R6xSWyVX/ZWk493PCxGQlhI/iqxh4M8I= cloud.google.com/go/iam v1.12.0 h1:Aki3bX9aHUDKPHfnRJfDcTdVedvy6quGBQcTqx3DRXk= cloud.google.com/go/iam v1.12.0/go.mod h1:FEZ4lXpADAC2AIpQY7LANNjjwyQ2jK439CI2VaD+sLY= cloud.google.com/go/logging v1.19.0 h1:NCqhdVUg3wQ8Cobdf16FDSuTGi3+6+hdSBHrY5TsR6Q= @@ -16,12 +16,12 @@ cloud.google.com/go/longrunning v1.2.0 h1:WjYH3YHBGCxGJP9M4dWGHBfXr/cFIjMkNgWcJj cloud.google.com/go/longrunning v1.2.0/go.mod h1:5KMQALFGOCtFoi2xSOA1u3H7WKlhmckgiyFw7+LGQp0= cloud.google.com/go/monitoring v1.30.0 h1:r/d+JUbyKmJ8b07iznuKfzVzrIXTWxHQ3lBRm3x2LlY= cloud.google.com/go/monitoring v1.30.0/go.mod h1:htlUR0QWVMrjFzZmN4LGnMAve9xB/eduwjmINxVZ8RM= -cloud.google.com/go/storage v1.65.1 h1:LRRpBJUTf+OXDPX9jZUKZ3mSLIsz3htG+qUpeNZovyA= -cloud.google.com/go/storage v1.65.1/go.mod h1:UsS9OgFg/XHOSYakQ8ZtLWWeyGkk1WnmD/GsGfN0BHM= +cloud.google.com/go/storage v1.68.0 h1:gqrAMJ51OZjYgU6AJ2U60um90YQhSjq8HEIQNtJ4C/8= +cloud.google.com/go/storage v1.68.0/go.mod h1:UsS9OgFg/XHOSYakQ8ZtLWWeyGkk1WnmD/GsGfN0BHM= cloud.google.com/go/trace v1.16.0 h1:GmQovzFc5F0CNfl0VLgL64aoTtu7xsM0YajW2GlG9+E= cloud.google.com/go/trace v1.16.0/go.mod h1:r+bdAn16dKLSV1G2D5v3e58IlQlizfxWrUfjx7kM7X0= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0 h1:yzIYdwuro811Z27D3T80Wkd3rqZzb0K43nner7Eh1yE= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 h1:bN1gA3of5bXtbnLsRPrwfmbbe7A5UWFlcTHseujLnpc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 h1:jLdiS1vO+XJFyDSWRHBx56r4s/NNtcl5J6KyCcWUX/w= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0/go.mod h1:8lmpHY+1VRoteiOwyrQMDt1YGXOrFKCz+1wJW7n3ODY= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.57.0 h1:cSjUzZ7KU8hicTgzaSv9NmSyM9fTVK3y5lsBUl3wOis= @@ -32,40 +32,40 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= -github.com/aws/aws-sdk-go-v2 v1.44.0 h1:4IbaHhtzy+4h37z4JQyO9a2QsiCml3CNYHtq5hIHigo= -github.com/aws/aws-sdk-go-v2 v1.44.0/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= +github.com/aws/aws-sdk-go-v2 v1.47.1 h1:uOIZnp4PK3ZhKI0dNrJrhTEsLxbpXHTAJlwoS1pvAtw= +github.com/aws/aws-sdk-go-v2 v1.47.1/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8= -github.com/aws/aws-sdk-go-v2/config v1.32.40 h1:lAVC9gMmKusmqDRe32dPtgKl/BWvJmMJoWELKHCAObw= -github.com/aws/aws-sdk-go-v2/config v1.32.40/go.mod h1:8xOJLbe/hOj1g4PVsfJYV7O2byq+UGET1onDdUgbwqc= -github.com/aws/aws-sdk-go-v2/credentials v1.19.39 h1:XOg8LC3Kgnsa3WiPQjc7Bi8k5IBN92cPYfIV9XMFss0= -github.com/aws/aws-sdk-go-v2/credentials v1.19.39/go.mod h1:GonTDBQ+mTpCVNwaHjj0PagspfrYYMEqOx7FehoEP/I= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.40 h1:r5aGipEVgI9aT/tAGjdrPbDQvIAKdTrS3rUPQtG4Rmo= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.40/go.mod h1:vOD3CnPxAdkL6MWZeROkZsTlskklMFfgVFkHzx/oZpY= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.40 h1:UIXlbijuB2XK1Kr57fo8iIxCuaSHJzwZ1uo+2tbEYIk= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.40/go.mod h1:wcEsL6jscjZjVUinb0Q5qD/GXOG1yT3GNfmT9HuDwzU= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.40 h1:xLQVRDs2NddDmK9BEyh5KSlJ1Gpy5/GIJXrV6WcVGAE= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.40/go.mod h1:XRXnpFVFGLaEVK+olDdFIM1vNa04ETW452oFGEPUxAo= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.41 h1:nv/ILuCY0yXACzMQwvtt/HbqDDjemZiI0AeDbxGQlnU= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.41/go.mod h1:dzvOSpxaPqQ3j0xS6Lc1vyVuWW0RBj7s/QqYpzu3Q/0= +github.com/aws/aws-sdk-go-v2/config v1.33.6 h1:MBjkSTLczek/UgiK+EYPIoRTqE7gP8vtW3OFbFo7Nug= +github.com/aws/aws-sdk-go-v2/config v1.33.6/go.mod h1:grRAFzdAZJrwcbasJRg2MPvIrVjtlfXllHssN6+E1JE= +github.com/aws/aws-sdk-go-v2/credentials v1.20.6 h1:NpAFXCU7NzXNkdGK3zQTtsRJ+3v9tZQV0xcdRw8uBdw= +github.com/aws/aws-sdk-go-v2/credentials v1.20.6/go.mod h1:mcZCoiPnyMvP8VMNbygNX5lLqSlkYJIMPODylQMurOk= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 h1:8gALAAmacnIXh+z6VkdDanv4/IkG5APdg4DZLDTmLog= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1/go.mod h1:Z7IJhJU+poOdJjUR2wpyY21ossQ1XS/R3Lk9Msq5kM4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.10.0 h1:U8/A0RRBaEspzH1uul3JHLbypXwEGUkRkvoT9f0ATcM= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.10.0/go.mod h1:UELStX5KwtJNtQxa+UuF8dc3z4UYc40e8yHYJSozNwY= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.40 h1:gr3Fw1cxZXNCdeo/lQ7isHEHzvHVM7z75qb2zW9aMjw= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.40/go.mod h1:8z/9CmfnQhiuXD7Ykbcg4a/whSWsniE0ODSx9uwVzfk= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.41 h1:Q9DIKDuJix/oJnQxFpQ26L0EwVa/YNo4k2kbktrjQjE= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.41/go.mod h1:x+TuqkOIG1SZS0+yN54sExGA9ZpjhPO6vPdYnpTFX1M= -github.com/aws/aws-sdk-go-v2/service/s3 v1.108.0 h1:Yp+x5PKXEmoqHsgP/pAkBy5Tyq1UlXAzM0OInh0vxWw= -github.com/aws/aws-sdk-go-v2/service/s3 v1.108.0/go.mod h1:locV6DtXyp7Xzr2BG6jtsbeBi3YAWJ/CY4xUThYmIwQ= -github.com/aws/aws-sdk-go-v2/service/signin v1.6.0 h1:agcr0j8YeFEzdXNo17Rg9MbbjLRjrimabwNtji4e+lU= -github.com/aws/aws-sdk-go-v2/service/signin v1.6.0/go.mod h1:qU5PxgQ4JiUOOMotzfO3+5oUda5W+8JDVKyLQqlrJik= -github.com/aws/aws-sdk-go-v2/service/sso v1.34.0 h1:FxaN8/sn61DTXNI6Gt678tFJUY8iUsCchm6Y/F/RjaA= -github.com/aws/aws-sdk-go-v2/service/sso v1.34.0/go.mod h1:vu4OY6s8LJtT8BtYG2LD6BGSZMptkYn3o5hvCPB22jc= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.39.0 h1:crWKPeGYTBTuBxQ3p73kjfJvt4brUIsr+Fuypko8FxY= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.39.0/go.mod h1:HjjZVhaBz0JBR/kbWKThmNDhFKS7y6EURuk493tJk9Y= -github.com/aws/aws-sdk-go-v2/service/sts v1.46.0 h1:IZ63JdogSNNjex/jsODNv7jGDcO/xJYd9FsgyfCsp1g= -github.com/aws/aws-sdk-go-v2/service/sts v1.46.0/go.mod h1:I+rwAf3spG5dITBaAo3xXRowk8kiOhtU1kYxfvCTC44= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 h1:VMAdYqr4Jn/8ATs9BHC5riwrs0d6m1Z2ohFriSwZwm0= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0/go.mod h1:9APRWGLFITKD+xzWSIyT9V7QV4bNlEuIieWlzXgGFlI= +github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 h1:DzCCWLzcIRQ77F3DEUljud7bEjTgFOIKXP52NmVRyhU= +github.com/aws/aws-sdk-go-v2/service/signin v1.10.1/go.mod h1:xpo/geVldu8payT375WekctUzopG/hBU7miiqItMUlw= +github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 h1:Umtl/0YZhng4xndfW3lKJrYYP7NLEjI6bGXVomwLcs0= +github.com/aws/aws-sdk-go-v2/service/sso v1.38.1/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/SBzUUymbUQuZbSPImghg= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 h1:0HOqZXRvMytH6bFHVIc0oJX07sZjfhz0zXtjs6gdE8s= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.1/go.mod h1:26zA0GhDrLo+yiLI2yXWxqB1PdsShfLikoI7GOEgugM= github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ= github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= @@ -94,8 +94,8 @@ github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa5 github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= -github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcykSlxMNc= +github.com/docker/go-connections v0.8.2/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dsnet/compress v0.0.1 h1:PlZu0n3Tuv04TzpfPbrnI0HW/YwodEXDS+oPKahKF0Q= @@ -103,14 +103,14 @@ github.com/dsnet/compress v0.0.1/go.mod h1:Aw8dCMJ7RioblQeTqt88akK31OvO8Dhf5Jflh github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7gzE= -github.com/ebitengine/purego v0.10.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= +github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU= +github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= -github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ= -github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= +github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be h1:SWe0x6yfglnxuvOiYgTTnNq7QD/yvqthOh1RBI8Bj8w= +github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be/go.mod h1:PYEOlng9XcrulfyWpm49jECTPV0LT4q8cO7fLW/xwgk= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= @@ -139,22 +139,22 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= -github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= -github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/s2a-go v0.1.10 h1:EMp+aOuXN6l8cE/gjF5Bt+vyZxsUuyCWe9chDWR/+uU= +github.com/google/s2a-go v0.1.10/go.mod h1:pz4tyvwXvJLLbyrkh6FW1eS2zPUXMaTmyNhYtyP2tNw= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.20 h1:t/xL64VUoN69MuMRQuJETqYGOw4Z9mSRJK9epIEtwFk= -github.com/googleapis/enterprise-certificate-proxy v0.3.20/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w= -github.com/googleapis/gax-go/v2 v2.24.0 h1:myMaPYyF9MecEmvQqMqomIwn9t/4KCZN9qnwsS76wlg= -github.com/googleapis/gax-go/v2 v2.24.0/go.mod h1:IaTHBDd7NHxSCiu0vEs8pQZu4dGZrWwuSoxCnk16OFM= +github.com/googleapis/enterprise-certificate-proxy v0.3.22 h1:NU4XpII6jD+Dxcot94fqjE+AfJoE/lQP9q3faYGzC/c= +github.com/googleapis/enterprise-certificate-proxy v0.3.22/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w= +github.com/googleapis/gax-go/v2 v2.24.1 h1:AtqTN21IXMMWo99LiEVAiBfNNQmO40d8xUfZI640mc0= +github.com/googleapis/gax-go/v2 v2.24.1/go.mod h1:bWeBei0NVwaNZKb2y1HUBS7gLXIF3/Tu3pq7j8D2Tb0= github.com/gopherclass/go-shellquote v0.0.0-20200814145606-fab22d094485 h1:1bPYu0COEL28IzKZwQN+uQIGuX31YFr3r+m3TU6hqh8= github.com/gopherclass/go-shellquote v0.0.0-20200814145606-fab22d094485/go.mod h1:aSawckur6IQmYgHum1MMf1oU1g1uT1Hz2e+cMvrs2Ww= github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.74 h1:mymLUKThnV9wFvogOK8NnsMP9/vlhnjXY98gr2QIGW8= github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.74/go.mod h1:Bh9qYL8ehmDxSg14Tk8oxFCP90XHfs6NxV1D84884xA= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= -github.com/hashicorp/go-getter v1.8.9 h1:1AOTMUmz/S/GuqOTE6+bg6nwPXTEbKr3Tc/T/lVS7is= -github.com/hashicorp/go-getter v1.8.9/go.mod h1:qI7vH/m552bXutKe4UkWptOJl4bo2KeO/CSOoh4s0ps= +github.com/hashicorp/go-getter v1.8.10 h1:uufJp+uacA0fSDRxclsHkiE6yUQTKgwv5b25QexgVM8= +github.com/hashicorp/go-getter v1.8.10/go.mod h1:5HyKGCQmT+I3MGAM76vk/fWpktjwxn7xruCUr9CrVuo= github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA= github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= @@ -169,12 +169,12 @@ github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/moby/api v1.56.0 h1:GQzua3NA599ASSIICx0iFgiJeO9YkdDARvQsm23ZZuQ= -github.com/moby/moby/api v1.56.0/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk= -github.com/moby/moby/client v0.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs= -github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ= -github.com/nwaples/rardecode/v2 v2.4.1 h1:F7zNW2LdAuuBThHWXQaiFUGVD/sef299NfWSB1nHAl4= -github.com/nwaples/rardecode/v2 v2.4.1/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsRNb6IbvGVHRmw= +github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c= +github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk= +github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4= +github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc= +github.com/nwaples/rardecode/v2 v2.4.4 h1:6Pke+s1s4qnl1wnJF82C9a/DP4DvGRXZPaU2m9PKFSc= +github.com/nwaples/rardecode/v2 v2.4.4/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsRNb6IbvGVHRmw= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= @@ -186,16 +186,16 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= -github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= +github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 h1:jL3a8soXdzuTCcRnKhOmtcsVOObdDTFf4O2B403HPRU= +github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI= github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk= -github.com/shirou/gopsutil/v4 v4.26.8 h1:YQMTF/1J50B5+Y0vlo1eDRf5DoR7Gk69hY+8wjYkQeo= -github.com/shirou/gopsutil/v4 v4.26.8/go.mod h1:5O9FjBiXoTDFatIWjZZosqj4pV0DRtLx598xGbBehzM= +github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg= +github.com/shirou/gopsutil/v4 v4.26.10/go.mod h1:XpkIrcUMQhwte/dGxu57KtnMMFsbKelI7PP23zweKBk= github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= @@ -218,10 +218,10 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= -github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA= -github.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI= -github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw= -github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4= github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw= @@ -235,8 +235,8 @@ github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0 h1:NmLfL734pJhM0JKaYd2Y28+nY9dPRWYAAbxhRCrKXPw= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= +go.opentelemetry.io/contrib/detectors/gcp v1.45.0 h1:9jR0ZPRok9ryaOQ2Wx8rg5F7Aon59mxrqbVI60/vlBk= +go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= @@ -265,31 +265,31 @@ golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/api v0.294.0 h1:8gASjJxdtcIieB3OqbkLcF0FfbXVNqKtU5iozD1ssvA= -google.golang.org/api v0.294.0/go.mod h1:02qB8+Ox1ZFzcaKFMguy1nQLJmSIyvV6Ff4txJEXtl4= +google.golang.org/api v0.299.0 h1:b3K+ydSMd0kh6TQI6bJyApRQfqQX2MfSOaVkpM59mJw= +google.golang.org/api v0.299.0/go.mod h1:zlR3GVA8b2R5nv5Ij9UWe37StVB3cxDD7DBFi4ZFsHw= google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d h1:C9v1o0/4quuhOAfmRXA2j+we0PqZIp8traLdeogF3Ms= google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d/go.mod h1:Wz2wFJntZFmLGo7pLDXZ3wYk5hyc0Mb+SkHhDDXT+lU= -google.golang.org/genproto/googleapis/api v0.0.0-20260715232425-e75dac1f907d h1:QwnJwPte4XXAkhPu26LTDIahnsMSUV0kK8HkxbC+Pc4= -google.golang.org/genproto/googleapis/api v0.0.0-20260715232425-e75dac1f907d/go.mod h1:WRrQ7/7N19PypuT0fxLOL5Lq0waoiRri4FbtHDEKrGE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 h1:cYNAzI2sUwhmCcoj9TxvihSrqsxt6uIkj3rDRhSDmW4= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA= -google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0= -google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 h1:lrupDmKL3p5kEX1M92oan027eCKcouzjuPbH6YBK+Rs= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:q/3oV3jAi5vwelxsVAprMBC8BcM2zmNe+IjRGd+9/ks= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 h1:b0xCahf3FK2m2Cv0p4vTozGPWncCvLfwV86UNg8xWU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 4b1a178ceff6537de3a12bb13a7d8297f7b638ae Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 17 Nov 2026 22:39:19 +0100 Subject: [PATCH 6/7] review --- internal/app/archive/confine_unix_test.go | 170 ++++++++++++++++++++++ internal/app/archive/create.go | 29 +++- internal/app/fsutil/confine.go | 43 +++++- internal/app/fsutil/confine_test.go | 77 ++++++++++ internal/app/fsutil/confine_unix_test.go | 26 ++++ 5 files changed, 336 insertions(+), 9 deletions(-) diff --git a/internal/app/archive/confine_unix_test.go b/internal/app/archive/confine_unix_test.go index c055188..3300f2e 100644 --- a/internal/app/archive/confine_unix_test.go +++ b/internal/app/archive/confine_unix_test.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "slices" + "strings" "testing" "github.com/gameap/daemon/internal/app/fsutil" @@ -900,6 +901,175 @@ func TestSourceWalker_ServerDirReplacedDuringTheWalk(t *testing.T) { assert.Empty(t, entries) } +// learnedServerDirs is the list of a daemon that goes on learning of game +// servers: the ones it knows are a cache, filled as the panel names them. +type learnedServerDirs struct { + dirs []string +} + +func (d *learnedServerDirs) ServerDirs() []string { + return d.dirs +} + +// A game server directory is the innermost one only as far as the daemon knew +// when a path was placed in it. One it learns of afterwards, lying inside, is +// a boundary for the rest of the walk like any other: a link its tenant keeps +// does not reach the files of the outer server. +func TestSourceWalker_ServerDirLearnedDuringTheWalk(t *testing.T) { + t.Parallel() + + // newWalker stands in server "a" while it is the innermost game server + // directory. "child" is a plain directory of it so far. + newWalker := func(t *testing.T) (*sourceWalker, *sourceScope, *fsutil.Confined, *learnedServerDirs) { + t.Helper() + + workDir := tenantWorkDir(t) + for _, link := range []string{"servers-link", "node-link", "file-link"} { + require.NoError(t, os.Remove(filepath.Join(workDir, "servers", "a", link))) + } + + writeTree(t, workDir, map[string]string{"servers/a/child/deep/data.txt": "child"}) + require.NoError(t, os.Symlink("../../own.txt", filepath.Join(workDir, "servers", "a", "child", "deep", "leak"))) + require.NoError(t, os.Symlink("child/deep", filepath.Join(workDir, "servers", "a", "jump"))) + require.NoError(t, os.Symlink("child/deep/leak", filepath.Join(workDir, "servers", "a", "file-jump"))) + + known := &learnedServerDirs{dirs: []string{"servers/a", "servers/b"}} + confiner := fsutil.NewConfiner(workDir, fsutil.WithServerDirs(known)) + + base, err := confiner.Resolve("servers/a", fsutil.TargetTree) + require.NoError(t, err) + t.Cleanup(func() { _ = base.Close() }) + + w := &sourceWalker{ + ctx: context.Background(), + confiner: confiner, + limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, + } + t.Cleanup(w.close) + + scope, err := w.adopt(base, false) + require.NoError(t, err) + require.True(t, w.confined(scope)) + + return w, scope, base, known + } + + t.Run("server_elsewhere_learned", func(t *testing.T) { + t.Parallel() + + w, scope, _, known := newWalker(t) + + known.dirs = append(known.dirs, "servers/c") + + require.NoError(t, w.walk(scope, ".", ".", 0)) + assert.True(t, w.confined(scope), "a game server elsewhere leaves the scope as it was") + assert.Len(t, w.scopes, 1) + }) + + t.Run("directory_entered_is_read_through_a_root_of_its_own", func(t *testing.T) { + t.Parallel() + + w, scope, _, known := newWalker(t) + + // No link is left to follow: the directory has to be noticed as such. + for _, link := range []string{"child/deep/leak", "jump", "file-jump", "in-link"} { + require.NoError(t, scope.root.Remove(link)) + } + + known.dirs = append(known.dirs, "servers/a/child") + + require.NoError(t, w.walk(scope, ".", ".", 0)) + require.NotEmpty(t, w.entries) + + for _, e := range w.entries { + inChild := e.name == "child" || strings.HasPrefix(e.name, "child/") + + assert.Equal(t, inChild, e.root != scope.root, e.name) + } + }) + + t.Run("link_kept_in_it_is_refused", func(t *testing.T) { + t.Parallel() + + w, scope, _, known := newWalker(t) + + known.dirs = append(known.dirs, "servers/a/child") + + err := w.walk(scope, ".", ".", 0) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) + + t.Run("file_link_led_on_by_its_tenant_is_refused", func(t *testing.T) { + t.Parallel() + + w, scope, _, known := newWalker(t) + + known.dirs = append(known.dirs, "servers/a/child") + + err := w.walk(scope, "file-jump", "file-jump", 0) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) + + t.Run("link_into_its_middle_is_refused_from_the_next_source", func(t *testing.T) { + t.Parallel() + + w, _, base, known := newWalker(t) + + _, err := w.collect(base, "servers/a", []string{"cstrike"}) + require.NoError(t, err) + + known.dirs = append(known.dirs, "servers/a/child") + + _, err = w.collect(base, "servers/a", []string{"jump"}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "path escapes from parent") + }) +} + +// One directory can be placed under two names, and only one of them may show +// that it holds another game server directory. The scope shared by both +// placements goes by the one that does. +func TestSourceWalker_ScopePlacedUnderTwoNames(t *testing.T) { + t.Parallel() + + workDir := tenantWorkDir(t) + require.NoError(t, os.Symlink("servers", filepath.Join(workDir, "alias"))) + + confiner := fsutil.NewConfiner(workDir, fsutil.WithServerDirs( + knownServerDirs{"servers/a", "alias/a", "alias/a/cstrike"}, + )) + + w := &sourceWalker{ + ctx: context.Background(), + confiner: confiner, + limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, + } + defer w.close() + + spelled, err := confiner.Resolve("servers/a/own.txt", fsutil.TargetEntry) + require.NoError(t, err) + require.True(t, spelled.Innermost) + + aliased, err := confiner.Resolve("alias/a/own.txt", fsutil.TargetEntry) + require.NoError(t, err) + require.False(t, aliased.Innermost) + + scope, err := w.adopt(spelled, true) + require.NoError(t, err) + require.True(t, w.confined(scope)) + + again, err := w.adopt(aliased, true) + require.NoError(t, err) + + require.Same(t, scope, again) + assert.False(t, w.confined(scope)) +} + // Many sources, and many links to one game server directory, are read through // the roots already open: the walk must not hold a descriptor for each. func TestSourceWalker_SharesRoots(t *testing.T) { diff --git a/internal/app/archive/create.go b/internal/app/archive/create.go index 658fc92..ab23a0b 100644 --- a/internal/app/archive/create.go +++ b/internal/app/archive/create.go @@ -235,9 +235,13 @@ type sourceScope struct { dir os.FileInfo // path is where root stands, relative to the work directory. path string + // placed is the placement the scope was made of. + placed *fsutil.Confined // confined is set for a root standing in a game server directory that // holds no other one. Nothing read through it leads out of that directory, - // so the walk looks for no further boundary below it. + // so the walk looks for no further boundary below it. That holds for the + // game servers known when the root was placed, and the walk outlasts it: + // the flag is read through sourceWalker.confined. confined bool // owned roots are opened by the walker and closed with it. owned bool @@ -316,7 +320,10 @@ func (w *sourceWalker) adopt(placed *fsutil.Confined, owned bool) (*sourceScope, _ = placed.Root.Close() } - known.confined = known.confined || placed.Innermost + // One directory can be placed under several names, and a later + // placement knows of game servers an earlier one did not: the scope is + // confined only while every placement finds it so. + known.confined = known.confined && placed.Innermost return known, nil } @@ -325,6 +332,7 @@ func (w *sourceWalker) adopt(placed *fsutil.Confined, owned bool) (*sourceScope, root: placed.Root, dir: dir, path: placed.Scope, + placed: placed, confined: placed.Innermost, owned: owned, } @@ -334,6 +342,19 @@ func (w *sourceWalker) adopt(placed *fsutil.Confined, owned bool) (*sourceScope, return scope, nil } +// confined reports whether scope still stands in a game server directory that +// holds no other one. The daemon learns of game servers while the walk lasts, +// so the question is put anew before every directory entered and every link +// followed. A scope found to hold a game server directory stays unconfined: +// from then on its directories are asked about one by one. +func (w *sourceWalker) confined(scope *sourceScope) bool { + if scope.confined && !w.confiner.StillInnermost(scope.placed) { + scope.confined = false + } + + return scope.confined +} + func (w *sourceWalker) scopeOf(dir os.FileInfo) *sourceScope { for _, scope := range w.scopes { if os.SameFile(scope.dir, dir) { @@ -444,7 +465,7 @@ func (w *sourceWalker) walk(scope *sourceScope, rel, name string, symlinkDepth i // there would then be followed through that root too, out of the game server // directory again. func (w *sourceWalker) cross(scope *sourceScope, rel string) (*sourceScope, string, error) { - if scope.confined { + if w.confined(scope) { return nil, "", nil } @@ -504,7 +525,7 @@ func (w *sourceWalker) walkDir(scope *sourceScope, rel, name string, info os.Fil // directory is read through a root of its own from there on; any other // directory stays where it is. func (w *sourceWalker) enter(scope *sourceScope, rel string, info os.FileInfo) (*sourceScope, string, error) { - if scope.confined || rel == "." || !w.confiner.IsServerDir(info) { + if rel == "." || w.confined(scope) || !w.confiner.IsServerDir(info) { return scope, rel, nil } diff --git a/internal/app/fsutil/confine.go b/internal/app/fsutil/confine.go index 26b84dc..00ca9c2 100644 --- a/internal/app/fsutil/confine.go +++ b/internal/app/fsutil/confine.go @@ -114,8 +114,8 @@ func WithRoot(root string) ConfineOption { // Resolve places the path a request names, and nothing below it. An operation // that goes on from there by itself, as packing a tree does, crosses into the // game server directories below through the root it started with, unless that -// root is Innermost, or it asks IsServerDir about the directories it enters -// and Resolve about the links it follows. +// root is Innermost and stays so (StillInnermost), or it asks IsServerDir +// about the directories it enters and Resolve about the links it follows. type Confiner struct { workDir string serverDirs ServerDirLister @@ -145,8 +145,13 @@ type Confined struct { // no other one, going by the names the daemon knows them by. Whatever is // reached through such a root stays in the game server directory it // belongs to. Below any other root a game server directory may lie, with a - // boundary of its own. + // boundary of its own. The names are the ones known when the path was + // placed: an operation that lasts asks StillInnermost as it goes on. Innermost bool + + // known are the names the daemon knows the directory of Root by, as a + // boundary. + known []string } func (c *Confined) Close() error { @@ -198,6 +203,24 @@ func (c *Confiner) IsServerDir(info os.FileInfo) bool { }) } +// StillInnermost reports whether placed, found Innermost when it was placed, +// would be found so now. The game servers the daemon knows are learned as the +// panel names them, also while an operation lasts, and the directory of one +// can lie in the directory placed stands in. From then on it is a boundary the +// operation has to look for below placed. +// +// Nothing is looked up on disk: the names known now are held against the ones +// placed was found under, so a walk can ask before every directory it enters. +func (c *Confiner) StillInnermost(placed *Confined) bool { + if !placed.Innermost { + return false + } + + b := bounds{servers: c.serverNames()} + + return !slices.ContainsFunc(placed.known, b.holds) +} + // Resolve places a caller-supplied path. See Confiner for the model. func (c *Confiner) Resolve(p string, target Target) (*Confined, error) { rel, err := RootRel(p) @@ -389,6 +412,7 @@ func (b bounds) openNamed(work *os.Root, rel string, named []boundary) (*Confine } placed.Rel = relativeTo(rel, placed.Scope) + placed.known = []string{placed.Scope} // The boundary reached is not the innermost one named when that one is // not on disk, and the one enclosing it can hold more. placed.Innermost = inServer && !b.holds(placed.Scope) @@ -521,7 +545,9 @@ type placer struct { // nested is set while the daemon knows a game server directory by a name // below the boundary the walk stands in. nested bool - hops int + // known are the names the daemon knows that boundary by. + known []string + hops int } // place walks rel down from work, telling the boundaries by seen. The root of @@ -557,7 +583,13 @@ func (b bounds) place(work *os.Root, seen landmarks, rel string, target Target) return nil, ErrPathOutsideConfinement } - return &Confined{Root: p.root, Rel: p.at, Scope: p.scope, Innermost: p.inServer && !p.nested}, nil + return &Confined{ + Root: p.root, + Rel: p.at, + Scope: p.scope, + Innermost: p.inServer && !p.nested, + known: p.known, + }, nil } // leave closes the boundary the walk stands in. @@ -777,6 +809,7 @@ func (p *placer) cross(info os.FileInfo) error { p.root, p.scope, p.at = inner, dir, "." p.inRoot = p.inRoot || isRoot p.inServer = p.inServer || isServer + p.known = known p.nested = slices.ContainsFunc(known, p.bounds.holds) return nil diff --git a/internal/app/fsutil/confine_test.go b/internal/app/fsutil/confine_test.go index bd08aa3..f7432e0 100644 --- a/internal/app/fsutil/confine_test.go +++ b/internal/app/fsutil/confine_test.go @@ -3,6 +3,7 @@ package fsutil import ( "os" "path/filepath" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -515,6 +516,82 @@ func TestConfiner_Resolve_Innermost(t *testing.T) { } } +// learnedDirs is the list of a daemon that goes on learning of game servers. +type learnedDirs struct { + dirs []string +} + +func (d *learnedDirs) ServerDirs() []string { + return d.dirs +} + +// The daemon learns of game servers after a path was placed. One whose +// directory lies in the directory the path was placed in ends that directory +// being the innermost; one that lies anywhere else does not. +func TestConfiner_StillInnermost(t *testing.T) { + t.Parallel() + + known := []string{"servers/a", "servers/b"} + nested := []string{"servers/a", "servers/a/nested", "servers/b"} + + tests := []struct { + name string + known []string + root string + path string + learned string + want bool + }{ + {name: "nothing_learned", known: known, path: "servers/a/own.txt", want: true}, + {name: "neighbour_learned", known: known, path: "servers/a/own.txt", learned: "servers/c", want: true}, + {name: "dir_with_a_longer_name_learned", known: known, path: "servers/a/own.txt", learned: "servers/ab", want: true}, + {name: "nested_dir_learned", known: known, path: "servers/a/own.txt", learned: "servers/a/nested"}, + {name: "nested_dir_not_on_disk_learned", known: known, path: "servers/a/own.txt", learned: "servers/a/new"}, + { + name: "nested_dir_learned_in_another_letter_case", + known: known, path: "servers/a/own.txt", learned: "Servers/A/nested", + }, + {name: "never_the_innermost", known: known, path: "steamcmd/steamcmd.sh", learned: "servers/c"}, + { + name: "server_dir_held_by_another/dir_beside_it_learned", + known: nested, path: "servers/a/nested/deep.md", learned: "servers/a/sub", + want: true, + }, + { + name: "server_dir_held_by_another/nested_dir_learned", + known: nested, path: "servers/a/nested/deep.md", learned: "servers/a/nested/inner", + }, + { + name: "request_root_in_a_server_dir/dir_beside_it_learned", + known: known, root: "servers/a/sub", path: "servers/a/sub/inner.txt", learned: "servers/a/nested", + want: true, + }, + { + name: "request_root_in_a_server_dir/nested_dir_learned", + known: known, root: "servers/a/sub", path: "servers/a/sub/inner.txt", learned: "servers/a/sub/inner", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + lister := &learnedDirs{dirs: slices.Clone(tt.known)} + confiner := NewConfiner(confineTree(t), WithServerDirs(lister), WithRoot(tt.root)) + + placed, err := confiner.Resolve(tt.path, TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = placed.Close() }) + + if tt.learned != "" { + lister.dirs = append(lister.dirs, tt.learned) + } + + assert.Equal(t, tt.want, confiner.StillInnermost(placed)) + }) + } +} + // A boundary is compared by the name it is found under and then opened by that // name. The walk moves into the directory it opened only when that is the one // it compared; a name that has come to lead elsewhere in between is refused. diff --git a/internal/app/fsutil/confine_unix_test.go b/internal/app/fsutil/confine_unix_test.go index 7a00701..8364dc0 100644 --- a/internal/app/fsutil/confine_unix_test.go +++ b/internal/app/fsutil/confine_unix_test.go @@ -286,6 +286,32 @@ func TestConfiner_RequestRootKeepsTheServerDirBoundary(t *testing.T) { } } +// A path a link leads into a game server directory is placed by the walk, +// under the names the daemon knows that directory by. A game server learned +// afterwards is held against those names, not against the spelling of the path. +func TestConfiner_StillInnermost_PlacedThroughALink(t *testing.T) { + t.Parallel() + + workDir := confineTree(t) + require.NoError(t, os.Symlink(filepath.Join("servers", "a"), filepath.Join(workDir, "shortcut"))) + + lister := &learnedDirs{dirs: []string{"servers/a", "servers/b"}} + confiner := NewConfiner(workDir, WithServerDirs(lister)) + + placed, err := confiner.Resolve("shortcut/own.txt", TargetEntry) + require.NoError(t, err) + t.Cleanup(func() { _ = placed.Close() }) + + require.Equal(t, "servers/a", placed.Scope) + require.True(t, confiner.StillInnermost(placed)) + + lister.dirs = append(lister.dirs, "servers/b/inner") + assert.True(t, confiner.StillInnermost(placed)) + + lister.dirs = append(lister.dirs, "servers/a/nested") + assert.False(t, confiner.StillInnermost(placed)) +} + // A game server directory reached under a name the daemon does not know it by // is still that directory: the request is confined to it all the same, and // placed under the name the link leads to. From c471447d2a0f7cfe879724fd3ca0fffca4983fa1 Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 17 Nov 2026 23:02:49 +0100 Subject: [PATCH 7/7] Fix archive traversal confinement when server directory boundaries change --- internal/app/archive/confine_unix_test.go | 61 +++++++++++++++++++++++ internal/app/archive/create.go | 15 +++--- 2 files changed, 69 insertions(+), 7 deletions(-) diff --git a/internal/app/archive/confine_unix_test.go b/internal/app/archive/confine_unix_test.go index 3300f2e..9057bb4 100644 --- a/internal/app/archive/confine_unix_test.go +++ b/internal/app/archive/confine_unix_test.go @@ -1031,6 +1031,67 @@ func TestSourceWalker_ServerDirLearnedDuringTheWalk(t *testing.T) { }) } +// changingServerDirs lets a test publish a new membership snapshot on a lookup. +type changingServerDirs func() []string + +func (d changingServerDirs) ServerDirs() []string { return d() } + +// A boundary observed by identity must be resolved even when the enclosing +// scope's names still describe it as innermost. Membership can change between +// the identity lookup and placement, as the daemon learns another spelling. +func TestSourceWalker_ObservedBoundaryInConfinedScope(t *testing.T) { + t.Parallel() + + for _, source := range []string{"child", "jump"} { + t.Run(source, func(t *testing.T) { + t.Parallel() + + workDir := t.TempDir() + writeTree(t, workDir, map[string]string{ + "servers/a/own.txt": "outer", + "servers/a/child/data.txt": "child", + }) + require.NoError(t, os.Symlink("child", filepath.Join(workDir, "servers/a/jump"))) + require.NoError(t, os.Symlink("servers/a/child", filepath.Join(workDir, "child-alias"))) + + names := []string{"servers/a"} + publish := false + confiner := fsutil.NewConfiner(workDir, fsutil.WithServerDirs(changingServerDirs(func() []string { + snapshot := names + if publish { + publish = false + names = []string{"servers/a", "servers/a/child"} + } + return snapshot + }))) + base, err := confiner.Resolve("servers/a", fsutil.TargetTree) + require.NoError(t, err) + defer base.Close() + + w := &sourceWalker{ + ctx: context.Background(), confiner: confiner, + limits: &walkLimits{follow: true, maxEntries: defaultMaxFilesLimit()}, + } + defer w.close() + scope, err := w.adopt(base, false) + require.NoError(t, err) + require.True(t, w.confined(scope)) + + // The first lookup sees the boundary through an alias. The next + // lookup also knows its spelling below the enclosing scope. + names = []string{"servers/a", "child-alias"} + publish = true + require.NoError(t, w.walk(scope, source, source, 0)) + require.NotEmpty(t, w.entries) + for _, entry := range w.entries { + assert.NotSame(t, scope.root, entry.root, entry.name) + _, err := entry.root.ReadFile("../own.txt") + assert.Error(t, err, "the child root must refuse access to the outer server") + } + }) + } +} + // One directory can be placed under two names, and only one of them may show // that it holds another game server directory. The scope shared by both // placements goes by the one that does. diff --git a/internal/app/archive/create.go b/internal/app/archive/create.go index ab23a0b..d3685b3 100644 --- a/internal/app/archive/create.go +++ b/internal/app/archive/create.go @@ -239,7 +239,7 @@ type sourceScope struct { placed *fsutil.Confined // confined is set for a root standing in a game server directory that // holds no other one. Nothing read through it leads out of that directory, - // so the walk looks for no further boundary below it. That holds for the + // so the walk can skip placement of non-boundaries below it. That holds for the // game servers known when the root was placed, and the walk outlasts it: // the flag is read through sourceWalker.confined. confined bool @@ -426,7 +426,7 @@ func (w *sourceWalker) walk(scope *sourceScope, rel, name string, symlinkDepth i return nil } - into, intoRel, err := w.cross(scope, rel) + into, intoRel, err := w.cross(scope, rel, w.confiner.IsServerDir(info)) if err != nil { return err } @@ -458,14 +458,15 @@ func (w *sourceWalker) walk(scope *sourceScope, rel, name string, symlinkDepth i // cross returns where to go on reading rel of scope, when that lies behind a // boundary: the scope of the game server directory rel is, or the followed // link rel ends in, and the path there. What crosses no boundary is read -// through the root it stands in, and nothing is returned. +// through the root it stands in, and nothing is returned. A boundary already +// observed by identity takes precedence over the confined shortcut. // // The root of scope would follow a link wherever it leads below it, into the // middle of a game server directory as well, and the links the tenant keeps // there would then be followed through that root too, out of the game server // directory again. -func (w *sourceWalker) cross(scope *sourceScope, rel string) (*sourceScope, string, error) { - if w.confined(scope) { +func (w *sourceWalker) cross(scope *sourceScope, rel string, serverBoundary bool) (*sourceScope, string, error) { + if !serverBoundary && w.confined(scope) { return nil, "", nil } @@ -525,11 +526,11 @@ func (w *sourceWalker) walkDir(scope *sourceScope, rel, name string, info os.Fil // directory is read through a root of its own from there on; any other // directory stays where it is. func (w *sourceWalker) enter(scope *sourceScope, rel string, info os.FileInfo) (*sourceScope, string, error) { - if rel == "." || w.confined(scope) || !w.confiner.IsServerDir(info) { + if rel == "." || !w.confiner.IsServerDir(info) { return scope, rel, nil } - into, intoRel, err := w.cross(scope, rel) + into, intoRel, err := w.cross(scope, rel, true) if err != nil { return nil, "", errors.WithMessagef(err, "failed to enter game server directory %q", path.Join(scope.path, rel)) }