Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 1 addition & 36 deletions driver/docker-container/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"net"
"os"
"path"
"path/filepath"
"strings"
"sync/atomic"
"time"
Expand All @@ -26,7 +25,6 @@ import (
contextstore "github.com/docker/cli/cli/context/store"
"github.com/docker/cli/opts"
"github.com/moby/buildkit/client"
mobyarchive "github.com/moby/go-archive"
"github.com/moby/moby/api/pkg/stdcopy"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/mount"
Expand Down Expand Up @@ -369,16 +367,7 @@ func (d *Driver) copyLogs(ctx context.Context, l progress.SubLogger) error {
}

func (d *Driver) copyToContainer(ctx context.Context, files map[string][]byte) error {
srcPath, err := writeConfigFiles(files)
if err != nil {
return err
}
if srcPath != "" {
defer os.RemoveAll(srcPath)
}
srcArchive, err := mobyarchive.TarWithOptions(srcPath, &mobyarchive.TarOptions{
ChownOpts: &mobyarchive.ChownOpts{UID: 0, GID: 0},
})
srcArchive, err := tarConfigFiles(files)
if err != nil {
return err
}
Expand Down Expand Up @@ -622,30 +611,6 @@ func (l *logWriter) Write(dt []byte) (int, error) {
return len(dt), nil
}

func writeConfigFiles(m map[string][]byte) (_ string, err error) {
// Temp dir that will be copied to the container
tmpDir, err := os.MkdirTemp("", "buildkitd-config")
if err != nil {
return "", err
}
defer func() {
if err != nil {
os.RemoveAll(tmpDir)
}
}()
configDir := filepath.Base(confutil.DefaultBuildKitConfigDir)
for f, dt := range m {
p := filepath.Join(tmpDir, configDir, f)
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
return "", err
}
if err := os.WriteFile(p, dt, 0644); err != nil {
return "", err
}
}
return tmpDir, nil
}

func getBuildkitFlags(initConfig driver.InitConfig) []string {
flags := initConfig.BuildkitdFlags
if _, ok := initConfig.Files[buildkitdConfigFile]; ok {
Expand Down
127 changes: 127 additions & 0 deletions driver/docker-container/tar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package docker

import (
"archive/tar"
"bytes"
"io"
"io/fs"
"maps"
"path"
"slices"
"strings"

"github.com/docker/buildx/util/confutil"
"github.com/pkg/errors"
)

const (
tarDirMode int64 = 0o755
tarFileMode int64 = 0o644
)

type configTarEntry struct {
name string
data []byte
}

func tarConfigFiles(files map[string][]byte) (io.ReadCloser, error) {
entries, dirs, err := configTarEntries(path.Base(confutil.DefaultBuildKitConfigDir), files)
if err != nil {
return nil, err
}
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
if err := writeConfigTar(tw, dirs, entries); err != nil {
_ = tw.Close()
return nil, err
}
if err := tw.Close(); err != nil {
return nil, err
}
return io.NopCloser(bytes.NewReader(buf.Bytes())), nil
}

func configTarEntries(configDir string, files map[string][]byte) ([]configTarEntry, []string, error) {
configDir, err := configArchiveRoot(configDir)
if err != nil {
return nil, nil, err
}

entries := make([]configTarEntry, 0, len(files))
dirs := map[string]struct{}{}
filePaths := make(map[string]struct{}, len(files))
if len(files) > 0 {
dirs[configDir] = struct{}{}
}
Comment on lines +53 to +55

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

configDir is the only name reaching writeConfigTar without passing configArchivePath. It's safe today only because len(files) > 0 makes it a prefix of every validated path. Would it be worth asserting it explicitly as well?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, fair point. configDir is currently derived from path.Base(confutil.DefaultBuildKitConfigDir), so it's buildkit today, but it's still the one path component added to the archive before going through the same explicit validation path. I will tighten that so the archive root is validated too, or refactor it so we don't pass an arbitrary root string around.


for _, name := range slices.Sorted(maps.Keys(files)) {
archivePath, err := configArchivePath(configDir, name)
if err != nil {
return nil, nil, err
}
entries = append(entries, configTarEntry{
name: archivePath,
data: files[name],
})
filePaths[archivePath] = struct{}{}
for dir := path.Dir(archivePath); dir != "."; dir = path.Dir(dir) {
dirs[dir] = struct{}{}
}
}

for filePath := range filePaths {
if _, ok := dirs[filePath]; ok {
return nil, nil, errors.Errorf("config file path %q conflicts with directory", strings.TrimPrefix(filePath, configDir+"/"))
}
}

return entries, slices.Sorted(maps.Keys(dirs)), nil
}

func configArchiveRoot(name string) (string, error) {
if name == "." || strings.Contains(name, "/") || strings.Contains(name, `\`) || strings.ContainsRune(name, 0) || !fs.ValidPath(name) {
return "", errors.Errorf("invalid config archive root %q", name)
}
return name, nil
}

func configArchivePath(configDir, name string) (string, error) {
if strings.Contains(name, `\`) || strings.ContainsRune(name, 0) {
return "", errors.Errorf("invalid config file path %q", name)
}
// Validate the literal slash path. path.Join would clean traversal first.
archivePath := configDir + "/" + name
if !fs.ValidPath(archivePath) {
return "", errors.Errorf("invalid config file path %q", name)
}
return archivePath, nil
}

func writeConfigTar(tw *tar.Writer, dirs []string, entries []configTarEntry) error {
for _, dir := range dirs {
if err := tw.WriteHeader(&tar.Header{

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we force a format format here? I think Go should select the appropriate one, but something to potentially be aware of.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think leaving Format unset is the right behavior here. The stdlib writer will pick the first format that can encode the header, which keeps simple paths as simple tar headers and still allows longer generated registry paths if needed. Forcing USTAR would make some valid config paths fail, and forcing PAX would add extended headers even when they are not needed.

Name: dir + "/",
Typeflag: tar.TypeDir,
Mode: tarDirMode,
}); err != nil {
return err
}
}
for _, entry := range entries {
if err := tw.WriteHeader(&tar.Header{
Name: entry.name,
Typeflag: tar.TypeReg,
Mode: tarFileMode,
Size: int64(len(entry.data)),
}); err != nil {
return err
}
if len(entry.data) == 0 {
continue
}
if _, err := tw.Write(entry.data); err != nil {
return err
}
}
return nil
}
161 changes: 161 additions & 0 deletions driver/docker-container/tar_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package docker

import (
"archive/tar"
"io"
"testing"

"github.com/stretchr/testify/require"
)

type tarEntry struct {
header *tar.Header
body []byte
}

func TestTarConfigFiles(t *testing.T) {
files := map[string][]byte{
"buildkitd.toml": []byte("debug = true\n"),
"certs/example.com/ca.pem": []byte("certificate"),
}

rc, err := tarConfigFiles(files)
require.NoError(t, err)
defer rc.Close()

expected := []string{
"buildkit/",
"buildkit/certs/",
"buildkit/certs/example.com/",
"buildkit/buildkitd.toml",
"buildkit/certs/example.com/ca.pem",
}
entries, names := readTarEntries(t, rc)
require.Equal(t, expected, names)
require.Len(t, entries, len(expected))
for _, name := range expected {
entry, ok := entries[name]
require.Truef(t, ok, "missing archive entry %q", name)
require.Equal(t, 0, entry.header.Uid)
require.Equal(t, 0, entry.header.Gid)
require.Empty(t, entry.header.Uname)
require.Empty(t, entry.header.Gname)
}

require.Equal(t, byte(tar.TypeDir), entries["buildkit/"].header.Typeflag)
require.Equal(t, tarDirMode, entries["buildkit/"].header.Mode)
require.Equal(t, files["buildkitd.toml"], entries["buildkit/buildkitd.toml"].body)
require.Equal(t, tarFileMode, entries["buildkit/buildkitd.toml"].header.Mode)
require.Equal(t, files["certs/example.com/ca.pem"], entries["buildkit/certs/example.com/ca.pem"].body)
}

func TestTarConfigFilesSnapshotsContent(t *testing.T) {
files := map[string][]byte{
"buildkitd.toml": []byte("debug = true\n"),
}

rc, err := tarConfigFiles(files)
require.NoError(t, err)
defer rc.Close()

files["buildkitd.toml"][0] = '#'

entries, _ := readTarEntries(t, rc)
require.Equal(t, []byte("debug = true\n"), entries["buildkit/buildkitd.toml"].body)
}

func TestTarConfigFilesEmpty(t *testing.T) {
rc, err := tarConfigFiles(nil)
require.NoError(t, err)
defer rc.Close()

tr := tar.NewReader(rc)
_, err = tr.Next()
require.ErrorIs(t, err, io.EOF)
}

func TestTarConfigFilesRejectsInvalidPaths(t *testing.T) {
for _, tc := range []struct {
name string
path string
}{
{name: "empty", path: ""},
{name: "dot", path: "."},
{name: "leading-dot", path: "./buildkitd.toml"},
{name: "parent", path: "../buildkitd.toml"},
{name: "absolute", path: "/buildkitd.toml"},
{name: "trailing-slash", path: "certs/"},
{name: "parent-element", path: "certs/../ca.pem"},
{name: "dot-element", path: "certs/./ca.pem"},
{name: "empty-element", path: "certs//ca.pem"},
{name: "backslash", path: `certs\ca.pem`},
{name: "nul", path: "certs/ca\x00.pem"},
} {
t.Run(tc.name, func(t *testing.T) {
rc, err := tarConfigFiles(map[string][]byte{
tc.path: []byte("invalid"),
})
require.Error(t, err)
require.Contains(t, err.Error(), "invalid config file path")
require.Nil(t, rc)
})
}
}

func TestTarConfigFilesRejectsFileDirectoryConflict(t *testing.T) {
rc, err := tarConfigFiles(map[string][]byte{
"certs": []byte("file"),
"certs/ca.pem": []byte("ca"),
})
require.Error(t, err)
require.Contains(t, err.Error(), "conflicts with directory")
require.Nil(t, rc)
}

func TestConfigTarEntriesRejectsInvalidRoot(t *testing.T) {
for _, tc := range []struct {
name string
root string
}{
{name: "empty", root: ""},
{name: "dot", root: "."},
{name: "parent", root: "../buildkit"},
{name: "absolute", root: "/buildkit"},
{name: "nested", root: "etc/buildkit"},
{name: "backslash", root: `etc\buildkit`},
{name: "nul", root: "build\x00kit"},
} {
t.Run(tc.name, func(t *testing.T) {
entries, dirs, err := configTarEntries(tc.root, map[string][]byte{
"buildkitd.toml": []byte("debug = true\n"),
})
require.Error(t, err)
require.Contains(t, err.Error(), "invalid config archive root")
require.Nil(t, entries)
require.Nil(t, dirs)
})
}
}

func readTarEntries(t *testing.T, r io.Reader) (map[string]tarEntry, []string) {
t.Helper()

tr := tar.NewReader(r)
entries := map[string]tarEntry{}
var names []string
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
require.NoError(t, err)
names = append(names, hdr.Name)
body, err := io.ReadAll(tr)
require.NoError(t, err)
entries[hdr.Name] = tarEntry{
header: new(*hdr),
body: body,
}
}
return entries, names
}
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ require (
github.com/in-toto/in-toto-golang v0.11.0
github.com/mitchellh/hashstructure/v2 v2.0.2
github.com/moby/buildkit v0.32.2
github.com/moby/go-archive v0.2.1
github.com/moby/moby/api v1.55.0
github.com/moby/moby/client v0.5.0
github.com/moby/policy-helpers v0.0.0-20260722051018-856be88baec4
Expand Down Expand Up @@ -167,13 +166,12 @@ require (
github.com/mattn/go-shellwords v1.0.12 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.2.0 // indirect
github.com/moby/locker v1.0.1 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/spdystream v0.5.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/signal v0.7.1 // indirect
github.com/moby/sys/user v0.4.1 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -399,8 +399,8 @@ github.com/moby/buildkit v0.32.2 h1:Sfy7+u6dUv/2yuBc9KCoK70Re8atuV8aPZ5UOC068Vc=
github.com/moby/buildkit v0.32.2/go.mod h1:0GB/EJ1d+4VIVqIAgy3asaoGkVXy7IrDfVy7mPhOvg8=
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/go-archive v0.2.1 h1:fAa0wUS/ikZKyx7o/1fhUYmhZ7RgpthdeoDhJvunTLc=
github.com/moby/go-archive v0.2.1/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE=
github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=
github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=
github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg=
github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc=
github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
Expand Down
Loading
Loading