Skip to content

Commit 906c232

Browse files
authored
Merge pull request containerd#10307 from henry118/uidmap
Support multiple uid/gid mappings [1/2]
2 parents a448047 + 83aaa89 commit 906c232

File tree

6 files changed

+557
-72
lines changed

6 files changed

+557
-72
lines changed

client/container_opts_unix.go

Lines changed: 48 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,32 +27,55 @@ import (
2727

2828
"github.com/containerd/containerd/v2/core/containers"
2929
"github.com/containerd/containerd/v2/core/mount"
30+
"github.com/containerd/containerd/v2/internal/userns"
31+
3032
"github.com/containerd/errdefs"
3133
"github.com/opencontainers/image-spec/identity"
34+
"github.com/opencontainers/runtime-spec/specs-go"
3235
)
3336

3437
// WithRemappedSnapshot creates a new snapshot and remaps the uid/gid for the
3538
// filesystem to be used by a container with user namespaces
3639
func WithRemappedSnapshot(id string, i Image, uid, gid uint32) NewContainerOpts {
37-
return withRemappedSnapshotBase(id, i, uid, gid, false)
40+
uidmaps := []specs.LinuxIDMapping{{ContainerID: 0, HostID: uid, Size: 65536}}
41+
gidmaps := []specs.LinuxIDMapping{{ContainerID: 0, HostID: gid, Size: 65536}}
42+
return withRemappedSnapshotBase(id, i, uidmaps, gidmaps, false)
43+
}
44+
45+
// WithUserNSRemappedSnapshot creates a new snapshot and remaps the uid/gid for the
46+
// filesystem to be used by a container with user namespaces
47+
func WithUserNSRemappedSnapshot(id string, i Image, uidmaps, gidmaps []specs.LinuxIDMapping) NewContainerOpts {
48+
return withRemappedSnapshotBase(id, i, uidmaps, gidmaps, false)
3849
}
3950

4051
// WithRemappedSnapshotView is similar to WithRemappedSnapshot but rootfs is mounted as read-only.
4152
func WithRemappedSnapshotView(id string, i Image, uid, gid uint32) NewContainerOpts {
42-
return withRemappedSnapshotBase(id, i, uid, gid, true)
53+
uidmaps := []specs.LinuxIDMapping{{ContainerID: 0, HostID: uid, Size: 65536}}
54+
gidmaps := []specs.LinuxIDMapping{{ContainerID: 0, HostID: gid, Size: 65536}}
55+
return withRemappedSnapshotBase(id, i, uidmaps, gidmaps, true)
4356
}
4457

45-
func withRemappedSnapshotBase(id string, i Image, uid, gid uint32, readonly bool) NewContainerOpts {
58+
// WithUserNSRemappedSnapshotView is similar to WithUserNSRemappedSnapshot but rootfs is mounted as read-only.
59+
func WithUserNSRemappedSnapshotView(id string, i Image, uidmaps, gidmaps []specs.LinuxIDMapping) NewContainerOpts {
60+
return withRemappedSnapshotBase(id, i, uidmaps, gidmaps, true)
61+
}
62+
63+
func withRemappedSnapshotBase(id string, i Image, uidmaps, gidmaps []specs.LinuxIDMapping, readonly bool) NewContainerOpts {
4664
return func(ctx context.Context, client *Client, c *containers.Container) error {
4765
diffIDs, err := i.(*image).i.RootFS(ctx, client.ContentStore(), client.platform)
4866
if err != nil {
4967
return err
5068
}
5169

52-
var (
53-
parent = identity.ChainID(diffIDs).String()
54-
usernsID = fmt.Sprintf("%s-%d-%d", parent, uid, gid)
55-
)
70+
rsn := remappedSnapshot{
71+
Parent: identity.ChainID(diffIDs).String(),
72+
IDMap: userns.IDMap{UidMap: uidmaps, GidMap: gidmaps},
73+
}
74+
usernsID, err := rsn.ID()
75+
if err != nil {
76+
return fmt.Errorf("failed to remap snapshot: %w", err)
77+
}
78+
5679
c.Snapshotter, err = client.resolveSnapshotterName(ctx, c.Snapshotter)
5780
if err != nil {
5881
return err
@@ -70,11 +93,11 @@ func withRemappedSnapshotBase(id string, i Image, uid, gid uint32, readonly bool
7093
return err
7194
}
7295
}
73-
mounts, err := snapshotter.Prepare(ctx, usernsID+"-remap", parent)
96+
mounts, err := snapshotter.Prepare(ctx, usernsID+"-remap", rsn.Parent)
7497
if err != nil {
7598
return err
7699
}
77-
if err := remapRootFS(ctx, mounts, uid, gid); err != nil {
100+
if err := remapRootFS(ctx, mounts, rsn.IDMap); err != nil {
78101
snapshotter.Remove(ctx, usernsID)
79102
return err
80103
}
@@ -95,22 +118,30 @@ func withRemappedSnapshotBase(id string, i Image, uid, gid uint32, readonly bool
95118
}
96119
}
97120

98-
func remapRootFS(ctx context.Context, mounts []mount.Mount, uid, gid uint32) error {
121+
func remapRootFS(ctx context.Context, mounts []mount.Mount, idMap userns.IDMap) error {
99122
return mount.WithTempMount(ctx, mounts, func(root string) error {
100-
return filepath.Walk(root, incrementFS(root, uid, gid))
123+
return filepath.Walk(root, chown(root, idMap))
101124
})
102125
}
103126

104-
func incrementFS(root string, uidInc, gidInc uint32) filepath.WalkFunc {
127+
func chown(root string, idMap userns.IDMap) filepath.WalkFunc {
105128
return func(path string, info os.FileInfo, err error) error {
106129
if err != nil {
107130
return err
108131
}
109-
var (
110-
stat = info.Sys().(*syscall.Stat_t)
111-
u, g = int(stat.Uid + uidInc), int(stat.Gid + gidInc)
112-
)
132+
stat := info.Sys().(*syscall.Stat_t)
133+
h, cerr := idMap.ToHost(userns.User{Uid: stat.Uid, Gid: stat.Gid})
134+
if cerr != nil {
135+
return cerr
136+
}
113137
// be sure the lchown the path as to not de-reference the symlink to a host file
114-
return os.Lchown(path, u, g)
138+
if cerr = os.Lchown(path, int(h.Uid), int(h.Gid)); cerr != nil {
139+
return cerr
140+
}
141+
// we must retain special permissions such as setuid, setgid and sticky bits
142+
if mode := info.Mode(); mode&os.ModeSymlink == 0 && mode&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
143+
return os.Chmod(path, mode)
144+
}
145+
return nil
115146
}
116147
}

client/snapshotter_opts_unix.go

Lines changed: 53 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,14 @@ package client
2020

2121
import (
2222
"context"
23+
"encoding/json"
2324
"fmt"
25+
"slices"
2426

2527
"github.com/containerd/containerd/v2/core/snapshots"
28+
"github.com/containerd/containerd/v2/internal/userns"
29+
"github.com/opencontainers/go-digest"
30+
"github.com/opencontainers/runtime-spec/specs-go"
2631
)
2732

2833
const (
@@ -58,15 +63,15 @@ func resolveSnapshotOptions(ctx context.Context, client *Client, snapshotterName
5863
}
5964

6065
needsRemap := false
61-
var uidMap, gidMap string
66+
var uidMapLabel, gidMapLabel string
6267

6368
if value, ok := local.Labels[snapshots.LabelSnapshotUIDMapping]; ok {
6469
needsRemap = true
65-
uidMap = value
70+
uidMapLabel = value
6671
}
6772
if value, ok := local.Labels[snapshots.LabelSnapshotGIDMapping]; ok {
6873
needsRemap = true
69-
gidMap = value
74+
gidMapLabel = value
7075
}
7176

7277
if !needsRemap {
@@ -84,33 +89,41 @@ func resolveSnapshotOptions(ctx context.Context, client *Client, snapshotterName
8489
return "", fmt.Errorf("snapshotter %q doesn't support idmap mounts on this host, configure `slow_chown` to allow a slower and expensive fallback", snapshotterName)
8590
}
8691

87-
var ctrUID, hostUID, length uint32
88-
_, err = fmt.Sscanf(uidMap, "%d:%d:%d", &ctrUID, &hostUID, &length)
92+
var uidMap, gidMap specs.LinuxIDMapping
93+
_, err = fmt.Sscanf(uidMapLabel, "%d:%d:%d", &uidMap.ContainerID, &uidMap.HostID, &uidMap.Size)
8994
if err != nil {
90-
return "", fmt.Errorf("uidMap unparsable: %w", err)
95+
return "", fmt.Errorf("uidMapLabel unparsable: %w", err)
9196
}
92-
93-
var ctrGID, hostGID, lengthGID uint32
94-
_, err = fmt.Sscanf(gidMap, "%d:%d:%d", &ctrGID, &hostGID, &lengthGID)
97+
_, err = fmt.Sscanf(gidMapLabel, "%d:%d:%d", &gidMap.ContainerID, &gidMap.HostID, &gidMap.Size)
9598
if err != nil {
96-
return "", fmt.Errorf("gidMap unparsable: %w", err)
99+
return "", fmt.Errorf("gidMapLabel unparsable: %w", err)
100+
}
101+
102+
if uidMap.ContainerID != 0 || gidMap.ContainerID != 0 {
103+
return "", fmt.Errorf("Container UID/GID of 0 only supported currently (%d/%d)", uidMap.ContainerID, gidMap.ContainerID)
97104
}
98105

99-
if ctrUID != 0 || ctrGID != 0 {
100-
return "", fmt.Errorf("Container UID/GID of 0 only supported currently (%d/%d)", ctrUID, ctrGID)
106+
rsn := remappedSnapshot{
107+
Parent: parent,
108+
IDMap: userns.IDMap{
109+
UidMap: []specs.LinuxIDMapping{uidMap},
110+
GidMap: []specs.LinuxIDMapping{gidMap},
111+
},
112+
}
113+
usernsID, err := rsn.ID()
114+
if err != nil {
115+
return "", fmt.Errorf("failed to remap snapshot: %w", err)
101116
}
102117

103-
// TODO(dgl): length isn't taken into account for the intermediate snapshot id.
104-
usernsID := fmt.Sprintf("%s-%d-%d", parent, hostUID, hostGID)
105118
if _, err := snapshotter.Stat(ctx, usernsID); err == nil {
106119
return usernsID, nil
107120
}
108121
mounts, err := snapshotter.Prepare(ctx, usernsID+"-remap", parent)
109122
if err != nil {
110123
return "", err
111124
}
112-
// TODO(dgl): length isn't taken into account here yet either.
113-
if err := remapRootFS(ctx, mounts, hostUID, hostGID); err != nil {
125+
126+
if err := remapRootFS(ctx, mounts, rsn.IDMap); err != nil {
114127
snapshotter.Remove(ctx, usernsID+"-remap")
115128
return "", err
116129
}
@@ -120,3 +133,27 @@ func resolveSnapshotOptions(ctx context.Context, client *Client, snapshotterName
120133

121134
return usernsID, nil
122135
}
136+
137+
type remappedSnapshot struct {
138+
Parent string `json:"Parent"`
139+
IDMap userns.IDMap `json:"IDMap"`
140+
}
141+
142+
func (s *remappedSnapshot) ID() (string, error) {
143+
compare := func(a, b specs.LinuxIDMapping) int {
144+
if a.ContainerID < b.ContainerID {
145+
return -1
146+
} else if a.ContainerID == b.ContainerID {
147+
return 0
148+
}
149+
return 1
150+
}
151+
slices.SortStableFunc(s.IDMap.UidMap, compare)
152+
slices.SortStableFunc(s.IDMap.GidMap, compare)
153+
154+
buf, err := json.Marshal(s)
155+
if err != nil {
156+
return "", err
157+
}
158+
return digest.FromBytes(buf).String(), nil
159+
}

cmd/ctr/commands/run/run_unix.go

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import (
3737
"github.com/containerd/containerd/v2/pkg/oci"
3838
"github.com/containerd/log"
3939
"github.com/containerd/platforms"
40+
4041
"github.com/intel/goresctrl/pkg/blockio"
4142
"github.com/opencontainers/runtime-spec/specs-go"
4243
"github.com/urfave/cli/v2"
@@ -45,13 +46,13 @@ import (
4546
)
4647

4748
var platformRunFlags = []cli.Flag{
48-
&cli.StringFlag{
49+
&cli.StringSliceFlag{
4950
Name: "uidmap",
50-
Usage: "Run inside a user namespace with the specified UID mapping range; specified with the format `container-uid:host-uid:length`",
51+
Usage: "Run inside a user namespace with the specified UID mapping ranges; specified with the format `container-uid:host-uid:length`",
5152
},
52-
&cli.StringFlag{
53+
&cli.StringSliceFlag{
5354
Name: "gidmap",
54-
Usage: "Run inside a user namespace with the specified GID mapping range; specified with the format `container-gid:host-gid:length`",
55+
Usage: "Run inside a user namespace with the specified GID mapping ranges; specified with the format `container-gid:host-gid:length`",
5556
},
5657
&cli.BoolFlag{
5758
Name: "remap-labels",
@@ -159,26 +160,28 @@ func NewContainer(ctx context.Context, client *containerd.Client, cliContext *cl
159160
containerd.WithImageConfigLabels(image),
160161
containerd.WithAdditionalContainerLabels(labels),
161162
containerd.WithSnapshotter(snapshotter))
162-
if uidmap, gidmap := cliContext.String("uidmap"), cliContext.String("gidmap"); uidmap != "" && gidmap != "" {
163-
uidMap, err := parseIDMapping(uidmap)
164-
if err != nil {
163+
164+
if uidmaps, gidmaps := cliContext.StringSlice("uidmap"), cliContext.StringSlice("gidmap"); len(uidmaps) > 0 && len(gidmaps) > 0 {
165+
var uidSpec, gidSpec []specs.LinuxIDMapping
166+
if uidSpec, err = parseIDMappingOption(uidmaps); err != nil {
165167
return nil, err
166168
}
167-
gidMap, err := parseIDMapping(gidmap)
168-
if err != nil {
169+
if gidSpec, err = parseIDMappingOption(gidmaps); err != nil {
169170
return nil, err
170171
}
171-
opts = append(opts,
172-
oci.WithUserNamespace([]specs.LinuxIDMapping{uidMap}, []specs.LinuxIDMapping{gidMap}))
172+
opts = append(opts, oci.WithUserNamespace(uidSpec, gidSpec))
173173
// use snapshotter opts or the remapped snapshot support to shift the filesystem
174174
// currently the snapshotters known to support the labels are:
175175
// fuse-overlayfs - https://github.com/containerd/fuse-overlayfs-snapshotter
176176
// overlay - in case of idmapped mount points are supported by host kernel (Linux kernel 5.19)
177177
if cliContext.Bool("remap-labels") {
178-
cOpts = append(cOpts, containerd.WithNewSnapshot(id, image,
179-
containerd.WithRemapperLabels(0, uidMap.HostID, 0, gidMap.HostID, uidMap.Size)))
178+
// TODO: the optimization code path on id mapped mounts only supports single mapping entry today.
179+
if len(uidSpec) > 1 || len(gidSpec) > 1 {
180+
return nil, errors.New("'remap-labels' option does not support multiple mappings")
181+
}
182+
cOpts = append(cOpts, containerd.WithNewSnapshot(id, image, containerd.WithRemapperLabels(0, uidSpec[0].HostID, 0, gidSpec[0].HostID, uidSpec[0].Size)))
180183
} else {
181-
cOpts = append(cOpts, containerd.WithRemappedSnapshot(id, image, uidMap.HostID, gidMap.HostID))
184+
cOpts = append(cOpts, containerd.WithUserNSRemappedSnapshot(id, image, uidSpec, gidSpec))
182185
}
183186
} else {
184187
// Even when "read-only" is set, we don't use KindView snapshot here. (#1495)
@@ -415,6 +418,18 @@ func NewContainer(ctx context.Context, client *containerd.Client, cliContext *cl
415418
return client.NewContainer(ctx, id, cOpts...)
416419
}
417420

421+
func parseIDMappingOption(stringSlices []string) ([]specs.LinuxIDMapping, error) {
422+
var res []specs.LinuxIDMapping
423+
for _, str := range stringSlices {
424+
m, err := parseIDMapping(str)
425+
if err != nil {
426+
return nil, err
427+
}
428+
res = append(res, m)
429+
}
430+
return res, nil
431+
}
432+
418433
func parseIDMapping(mapping string) (specs.LinuxIDMapping, error) {
419434
// We expect 3 parts, but limit to 4 to allow detection of invalid values.
420435
parts := strings.SplitN(mapping, ":", 4)

0 commit comments

Comments
 (0)