Skip to content

Commit 906656f

Browse files
authored
Merge pull request #5336 from danielcho02/cp-pin-destination
cp: keep host-to-container writes inside the container mount
2 parents 61ab411 + 9dea521 commit 906656f

4 files changed

Lines changed: 559 additions & 6 deletions

File tree

‎cmd/nerdctl/container/container_cp_linux_test.go‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030
"gotest.tools/v3/assert"
3131
"gotest.tools/v3/icmd"
3232

33+
"github.com/containerd/nerdctl/mod/tigron/require"
3334
"github.com/containerd/nerdctl/mod/tigron/test"
3435
"github.com/containerd/nerdctl/mod/tigron/tig"
3536

@@ -1078,3 +1079,68 @@ func cpContainerSubTest(description string, tc testcases, copyToContainer bool,
10781079
},
10791080
}
10801081
}
1082+
1083+
// TestCopyToContainerPinsDestination swaps the destination directory for a symlink to a host directory right before
1084+
// tar extracts, from a wrapper around tar, and checks that the copy still lands in the container.
1085+
func TestCopyToContainerPinsDestination(t *testing.T) {
1086+
testCase := nerdtest.Setup()
1087+
// The wrapper reaches the container through /proc/<pid>/root, and is picked up through $TAR by nerdctl only.
1088+
testCase.Require = require.All(require.Not(nerdtest.Docker), nerdtest.Rootful)
1089+
1090+
testCase.Setup = func(data test.Data, helpers test.Helpers) {
1091+
tarBinary, _, err := tarutil.FindTarBinary()
1092+
assert.NilError(t, err)
1093+
tempDir := t.TempDir()
1094+
outside := filepath.Join(tempDir, "outside")
1095+
assert.NilError(t, os.Mkdir(outside, dirPerm))
1096+
sourceFile := filepath.Join(tempDir, "payload")
1097+
assert.NilError(t, os.WriteFile(sourceFile, []byte(data.Identifier()), filePerm))
1098+
1099+
helpers.Ensure("run", "-d", "--name", data.Identifier(), testutil.CommonImage, "sleep", nerdtest.Infinity)
1100+
nerdtest.EnsureContainerStarted(helpers, data.Identifier())
1101+
helpers.Ensure("exec", data.Identifier(), "mkdir", "-p", "/data/x")
1102+
pid := strings.TrimSpace(helpers.Capture("inspect", "--format", "{{.State.Pid}}", data.Identifier()))
1103+
1104+
// Before extracting, move the destination aside and put a symlink to a host directory in its place, as a
1105+
// process in the container could.
1106+
dest := fmt.Sprintf("/proc/%s/root/data/x", pid)
1107+
wrapper := filepath.Join(tempDir, "tar")
1108+
script := fmt.Sprintf(`#!/bin/sh
1109+
for arg; do
1110+
if [ "$arg" = -x ]; then
1111+
mv %[1]q %[1]q.orig && ln -s %[2]q %[1]q || exit 1
1112+
fi
1113+
done
1114+
exec %[3]q "$@"
1115+
`, dest, outside, tarBinary)
1116+
assert.NilError(t, os.WriteFile(wrapper, []byte(script), 0o755))
1117+
1118+
data.Labels().Set("wrapper", wrapper)
1119+
data.Labels().Set("outside", outside)
1120+
data.Labels().Set("sourceFile", sourceFile)
1121+
}
1122+
1123+
testCase.Cleanup = func(data test.Data, helpers test.Helpers) {
1124+
helpers.Anyhow("rm", "-f", data.Identifier())
1125+
}
1126+
1127+
testCase.Command = func(data test.Data, helpers test.Helpers) test.TestableCommand {
1128+
cmd := helpers.Command("cp", data.Labels().Get("sourceFile"), data.Identifier()+":/data/x")
1129+
cmd.Setenv("TAR", data.Labels().Get("wrapper"))
1130+
return cmd
1131+
}
1132+
1133+
testCase.Expected = func(data test.Data, helpers test.Helpers) *test.Expected {
1134+
return &test.Expected{
1135+
Output: func(stdout string, t tig.T) {
1136+
entries, err := os.ReadDir(data.Labels().Get("outside"))
1137+
assert.NilError(t, err)
1138+
assert.Equal(t, len(entries), 0, "the copy followed the symlink out of the container")
1139+
assert.Equal(t, helpers.Capture("exec", data.Identifier(), "cat", "/data/x.orig/payload"), data.Identifier(),
1140+
"the copy did not land in the directory nerdctl opened")
1141+
},
1142+
}
1143+
}
1144+
1145+
testCase.Run(t)
1146+
}

‎pkg/containerutil/cp_linux.go‎

Lines changed: 157 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"os"
2626
"os/exec"
2727
"path/filepath"
28+
"slices"
2829
"strconv"
2930
"strings"
3031

@@ -60,6 +61,134 @@ var (
6061
ErrCannotCopyDirToFile = errors.New("cannot copy a directory to a file") // cp SOMEDIR foo:/etc/issue
6162
)
6263

64+
const (
65+
// procSelfFd is where a process finds its own file descriptors by number.
66+
procSelfFd = "/proc/self/fd/"
67+
// pinnedDirArg is how the tar process refers to the directory handed to it as the first entry of ExtraFiles,
68+
// which becomes its fd 3.
69+
pinnedDirArg = procSelfFd + "3"
70+
)
71+
72+
// openHostMount opens the container mount whose host path is mountRoot as an os.Root, and returns the path of
73+
// relativePath inside it. A mount of a single file is opened on its parent directory.
74+
func openHostMount(mountRoot, relativePath string) (*os.Root, string, error) {
75+
st, err := os.Stat(mountRoot)
76+
if err != nil {
77+
return nil, "", err
78+
}
79+
if !st.IsDir() {
80+
relativePath = filepath.Join(filepath.Base(mountRoot), relativePath)
81+
mountRoot = filepath.Dir(mountRoot)
82+
}
83+
root, err := os.OpenRoot(mountRoot)
84+
if err != nil {
85+
return nil, "", err
86+
}
87+
return root, relativePath, nil
88+
}
89+
90+
// openMountRoot opens the container mount that holds dest as an os.Root, and returns the path of dest inside it.
91+
// A mount of a single file is opened on its parent directory on the host.
92+
//
93+
// liveRoot is the root of the running container (/proc/<pid>/root), or "" when the container is not running.
94+
// The host path of a mount can be reachable from the container through another mount, so that a process in the
95+
// container can rename it and put a symlink in its place. In a running container, a directory mount is therefore
96+
// opened the way the container sees it, through liveRoot, and for a file mount the host file is checked to still
97+
// be the file mounted in the container.
98+
func openMountRoot(dest *pathSpecifier, liveRoot string) (*os.Root, string, error) {
99+
if !filepath.IsAbs(dest.mountRoot) {
100+
return nil, "", fmt.Errorf("cannot copy into mount with non-path source %q", dest.mountRoot)
101+
}
102+
rel := dest.relativePath
103+
if rel == "" {
104+
rel = "."
105+
}
106+
if liveRoot == "" {
107+
return openHostMount(dest.mountRoot, rel)
108+
}
109+
110+
container, err := os.OpenRoot(liveRoot)
111+
if err != nil {
112+
return nil, "", err
113+
}
114+
mountPath, err := filepath.Rel("/", dest.mountPath)
115+
if err != nil {
116+
container.Close()
117+
return nil, "", err
118+
}
119+
if mountPath == "." {
120+
return container, rel, nil
121+
}
122+
defer container.Close()
123+
124+
mounted, err := container.Stat(mountPath)
125+
if err != nil {
126+
return nil, "", err
127+
}
128+
if mounted.IsDir() {
129+
root, err := container.OpenRoot(mountPath)
130+
if err != nil {
131+
return nil, "", err
132+
}
133+
return root, rel, nil
134+
}
135+
136+
root, rel, err := openHostMount(dest.mountRoot, rel)
137+
if err != nil {
138+
return nil, "", err
139+
}
140+
source, err := root.Lstat(filepath.Base(dest.mountRoot))
141+
if err != nil || !os.SameFile(source, mounted) {
142+
root.Close()
143+
return nil, "", errors.Join(fmt.Errorf("source of mount %q is not the file mounted in the container", dest.mountPath), err)
144+
}
145+
return root, rel, nil
146+
}
147+
148+
// openExtractDir prepares a copy into the container: it creates the destination when it does not exist, and returns
149+
// a handle on the directory tar extracts into, which is the destination itself if intoDest, and its parent otherwise.
150+
// A process in the container can replace any component of the destination with a symlink after it has been
151+
// resolved, and absolute symlinks under /proc/<pid>/root are followed against the host root. Both operations go
152+
// through an os.Root on the container mount so that they stay inside it, and tar gets the handle rather than a path.
153+
// liveRoot is as for openMountRoot.
154+
func openExtractDir(dest *pathSpecifier, intoDest bool, liveRoot string) (*os.File, error) {
155+
root, rel, err := openMountRoot(dest, liveRoot)
156+
if err != nil {
157+
return nil, errors.Join(ErrFilesystem, err)
158+
}
159+
defer root.Close()
160+
161+
// XXX FIXME: this seems wrong. What about ownership? We could be doing that inside a container
162+
if !dest.exists {
163+
if err = root.Mkdir(rel, 0o755); err != nil {
164+
return nil, errors.Join(ErrFilesystem, err)
165+
}
166+
}
167+
168+
if !intoDest {
169+
rel = filepath.Dir(rel)
170+
}
171+
dir, err := root.OpenFile(rel, unix.O_PATH|unix.O_DIRECTORY, 0)
172+
if err != nil {
173+
return nil, errors.Join(ErrFilesystem, err)
174+
}
175+
return dir, nil
176+
}
177+
178+
// tarExtractCmd returns the command running tarX, a tar -x command line to which it appends -C and -f, so that tar
179+
// extracts the archive read from stdin into dir. If pinned (the handle from openExtractDir) is not nil, tar receives
180+
// it as its fd 3 and extracts there instead of resolving dir again.
181+
func tarExtractCmd(ctx context.Context, tarX []string, dir string, pinned *os.File) *exec.Cmd {
182+
var extraFiles []*os.File
183+
if pinned != nil {
184+
dir = pinnedDirArg
185+
extraFiles = []*os.File{pinned}
186+
}
187+
cmd := exec.CommandContext(ctx, tarX[0], append(slices.Clone(tarX[1:]), "-C", dir, "-f", "-")...)
188+
cmd.ExtraFiles = extraFiles
189+
return cmd
190+
}
191+
63192
// getRoot will tentatively return the root of the container on the host (/proc/pid/root), along with the pid,
64193
// (eg: doable when the container is running)
65194
func getRoot(ctx context.Context, container containerd.Container) (string, int, error) {
@@ -213,8 +342,21 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
213342
return ErrDestinationDirMustExist
214343
}
215344

216-
// XXX FIXME: this seems wrong. What about ownership? We could be doing that inside a container
217-
if !destinationSpec.exists {
345+
// tar extracts into the destination itself, or into its parent when copying a file to a new name
346+
intoDest := sourceSpec.isADir || destinationSpec.endsWithSeparator || (destinationSpec.exists && destinationSpec.isADir)
347+
348+
var tarXDirFile *os.File
349+
if !options.Container2Host {
350+
liveRoot := ""
351+
if pid != 0 {
352+
liveRoot = root
353+
}
354+
tarXDirFile, err = openExtractDir(destinationSpec, intoDest, liveRoot)
355+
if err != nil {
356+
return err
357+
}
358+
defer tarXDirFile.Close()
359+
} else if !destinationSpec.exists {
218360
if err = os.Mkdir(destinationSpec.resolvedPath, 0o755); err != nil {
219361
return errors.Join(ErrFilesystem, err)
220362
}
@@ -272,7 +414,7 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
272414
}
273415

274416
tarXDir := destinationSpec.resolvedPath
275-
if !sourceSpec.isADir && !destinationSpec.endsWithSeparator && !(destinationSpec.exists && destinationSpec.isADir) {
417+
if !intoDest {
276418
tarXDir = filepath.Dir(destinationSpec.resolvedPath)
277419
}
278420
var tarX []string
@@ -283,11 +425,15 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
283425
if options.Container2Host && isGNUTar {
284426
tarX = append(tarX, "--no-same-owner")
285427
}
286-
tarX = append(tarX, "-C", tarXDir, "-f", "-")
287428

288429
// tar opens the -C directory by itself and fails with an unhelpful error when the directory
289430
// is not accessible, so detect this beforehand.
290-
if accessErr := unix.Access(tarXDir, unix.X_OK); errors.Is(accessErr, unix.EACCES) {
431+
accessPath := tarXDir
432+
if tarXDirFile != nil {
433+
// this process has the handle under another number than tar
434+
accessPath = procSelfFd + strconv.Itoa(int(tarXDirFile.Fd()))
435+
}
436+
if accessErr := unix.Access(accessPath, unix.X_OK); errors.Is(accessErr, unix.EACCES) {
291437
return ErrTargetIsReadOnly
292438
}
293439
}
@@ -308,7 +454,12 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
308454
tarCCmd.Stdin = nil
309455
tarCCmd.Stderr = os.Stderr
310456

311-
tarXCmd := exec.CommandContext(ctx, tarX[0], tarX[1:]...)
457+
var tarXCmd *exec.Cmd
458+
if destinationSpec.toStdout {
459+
tarXCmd = exec.CommandContext(ctx, tarX[0], tarX[1:]...)
460+
} else {
461+
tarXCmd = tarExtractCmd(ctx, tarX, tarXDir, tarXDirFile)
462+
}
312463
if sourceSpec.fromStdin {
313464
// Reading from tar should pipe stdin into dst
314465
tarXCmd.Stdin = bufio.NewReader(os.Stdin)

0 commit comments

Comments
 (0)