Commit Graph

19 Commits

Author SHA1 Message Date
Sebastiaan van Stijn
5dd377a6ae pkg: modernize: mapsloop
go install golang.org/x/tools/go/analysis/passes/modernize/cmd/modernize@latest
    modernize -mapsloop -fix ./...

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2026-03-15 15:00:12 +01:00
Andrew Halaney
59cc4cc49d pkg/sys: Let more environments create user namespace as the initial user
By restoring the effective capabilities of the thread after setresuid()
we can both:

    1. Use the go runtime to setup the uid_map now that we have the
       capabilities to do so in the thread again
    2. Enable this on distro's which have restrictions around
       unprivileged user namespace creation and usage (since the thread
       is now privileged)

Let's do it. See [0] for more details on this topic. Unlike
unix::Setresuid()[1], which mimics the glibc implementation and acts on all
threads in the process, unix::Cap{s,g}et() are thread local[2] only as we
want, so we can use that directly.

[0]: https://github.com/containerd/containerd/pull/12317#discussion_r2686960671
[1]: e2fef50def/src/syscall/syscall_linux.go (L1217)
[2]: 6fb913b30f/unix/zsyscall_linux.go (L524)
Signed-off-by: Andrew Halaney <ahalaney@netflix.com>
2026-01-14 09:04:32 -06:00
Andrew Halaney
42ce92b222 pkg/sys: Create user namespace as the container's initial user namespace user
Right now containerd uses os.StartProcess() to create a dummy ptraced
process via a fork/exec in a new user namespace, with the uid_map/gid_map
setup.

This doesn't work so well with user limits[0] in the kernel, at least if
you expect the container user to have separate isolation from the host's
"normal users". The kernel's ucount mechanism forms a ucount tuple of (ns, kuid_t)
for each user limit. Say containerd runs as uid 0 in the initial user namespace,
and the container runs as uid 100000 from the inital user namespace point of view.

When the container tries to do things like inotify_add_watch(), the
kernel:

    1. First verifies that the ucount(container user namespace, 100000)
       doesn't exceed its "per user per user namespace limits" and
       increments the counter there. This limit is set by
       /proc/sys/user/max_inotify_watches when in the namespace
    2. Then walks up to the ucount who created this namespace,
       ucount(initial user namespace, 0) and increments their counter as
       well ensuring they don't exceed their limit. In our example this
       is the initial user namespace, this limit is set by
       /proc/sys/fs/inotify/max_user_watches as well as
       /proc/sys/user/max_inotify_watches in that case.

This is done so a user can't escape per user limits by creating a user
namespace and running as different users in that user namespace. The
accounting always rolls back up to the user who created the user
namespace to ensure this, checking limits at each layer.

This means if you have a rogue container they can consume all of
the containerd user's inotify limits. In practice this means global root
is in danger of being denied usage of resources due to the container,
while other less important users are still well within their budget!
In the inotify case for example systemd will fail to start many new
services due to this.

Let's instead create the user namespace *as the container's initial user
namespace user*. This means that all the attribution for these user
limits rolls up to this unimportant user, preventing one container from
exhausting global root's resources, and further isolating each container
from each other (since each pod in k8s runs as its own disjoint set of
users in the initial user namespace).

This is a bit annoying to do in golang. The best option seems to be what
we have here:

    1. Lock OS thread
    2. Manually setresuid() (seteuid implementation in golang mimics
       glibc's and sets the euid for all of the threads, which causes
       issues for other threads running at the same time)
    3. Create user namespace
    4. Undo the setresuid()
    5. Update the uid_map/gid_map as root now (can't do this anymore as
       part of (3) since to update the map you must have CAP_SETUID
       which the container user will not have)

With this in place you can verify the user namespace is owned by the
proper uid via ioctl(fd, NS_GET_OWNER_UID). Some distros block
unprivleged user namespace creation, for those we'll just continue to
create it as containerd's user.

[0]: https://docs.kernel.org/admin-guide/sysctl/user.html#documentation-for-proc-sys-user
Signed-off-by: Andrew Halaney <ahalaney@netflix.com>
2026-01-14 09:04:32 -06:00
Wei Fu
6ce7f6d87a pkg/sys: check SupportsPidFD first
Checking this earlier and bailing is preferable to checking this to after we
try to StartProcess.

Signed-off-by: Wei Fu <fuweid89@gmail.com>
2025-08-12 14:53:29 -04:00
Jose Fernandez
45e02e1dc1 sys: fix pidfd leak in UnshareAfterEnterUserns
UnshareAfterEnterUserns() creates a pidfd via os.StartProcess() with
CLONE_PIDFD but fails to close the file descriptor in any code path,
resulting in a file descriptor leak for every container that uses user
namespace isolation.

The leak occurs because:
- The pidfd is created when PidFD field is set in SysProcAttr
- The original defer block only calls PidfdSendSignal() and
  pidfdWaitid()
- No code path calls unix.Close(pidfd) to release the file descriptor

This causes one pidfd leak per container launch when user namespace
isolation is enabled (e.g., Kubernetes pods with hostUsers: false). In
production environments with high container churn, this can exhaust the
system's file descriptor limit.

Fix the leak by adding a defer statement immediately after process
creation that ensures unix.Close(pidfd) is always called, regardless of
which code path is taken. This guarantees cleanup even if the function
returns early due to errors or lack of pidfd support.

This follows the same cleanup pattern already established in
core/mount/mount_idmapped_utils_linux.go:getUsernsFD() which properly
closes its pidfd.

Closes: #12166
Signed-off-by: Jose Fernandez <josef@netflix.com>
2025-08-06 20:26:48 -06:00
Jin Dong
734d52c39c chore: remove specific go version code
Now that we have 1.24.x as go min version, I think
we can remove this go code specific to a lower
version.

Signed-off-by: Jin Dong <djdongjin95@gmail.com>
2025-06-12 21:35:09 -04:00
Sebastiaan van Stijn
1477874494 use lazyregexp to compile regexes on first use
- internal/cri/bandwidth: use lazyregexp to compile regexes on first use
- pkg/identifiers: use lazyregexp to compile regexes on first use
- pkg/progress: use lazyregexp to compile regexes on first use
- pkg/reference: use lazyregexp to compile regexes on first use
- pkg/sys: use lazyregexp to compile regexes on first use

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-22 20:29:14 +02:00
QiPing Wan
be9ca11a14 fix call fmt.Errorf with wrong error
Signed-off-by: QiPing Wan <alingse@foxmail.com>
2025-04-08 09:09:40 +08:00
ningmingxiao
1dbb7f2ae3 pkg/sys: improve GetLocalListener/CreateUnixSocket error message
Signed-off-by: ningmingxiao <ning.mingxiao@zte.com.cn>
2025-04-01 12:53:41 +08:00
Mike Baynton
347423a114 Request 'allow' setgroups when spawning new userns
Signed-off-by: Mike Baynton <mike@mbaynton.com>
2024-10-17 15:37:36 -05:00
Wei Fu
fd3f3d5a13 pkg/sys: add GetUsernsForNamespace interface
Signed-off-by: Wei Fu <fuweid89@gmail.com>
2024-09-11 07:21:43 +08:00
Wei Fu
490e45a08a pkg/sys: Add UnshareAfterEnterUserns function
It allows to disassociate parts of its execution context within a user
namespace.

Signed-off-by: Wei Fu <fuweid89@gmail.com>
2024-09-11 07:21:39 +08:00
Wei Fu
3cd8f9734d core/mount: use ptrace instead of go:linkname
The Go runtime has started to [lock down future uses of linkname][1] since
go1.23. In the go source code, containerd project has been marked in the
comment, [hall of shame][2]. Well, the go:linkname is used to fork no-op
subprocess efficiently. However, since that comment, I would like to use
ptrace and remove go:linkname in the whole repository.

With go1.22 `go:linkname`:

```bash
$ go test -bench=.  -benchmem ./ -exec sudo
goos: linux
goarch: amd64
pkg: github.com/containerd/containerd/v2/core/mount
cpu: AMD Ryzen 7 5800H with Radeon Graphics
BenchmarkBatchRunGetUsernsFD_Concurrent1-16                 2440            533320 ns/op            1145 B/op         43 allocs/op
BenchmarkBatchRunGetUsernsFD_Concurrent10-16                 342           3661616 ns/op           11562 B/op        421 allocs/op
PASS
ok      github.com/containerd/containerd/v2/core/mount  2.983s
```

With go1.22 `ptrace`:

```bash
$ go test -bench=.  -benchmem ./ -exec sudo
goos: linux
goarch: amd64
pkg: github.com/containerd/containerd/v2/core/mount
cpu: AMD Ryzen 7 5800H with Radeon Graphics
BenchmarkBatchRunGetUsernsFD_Concurrent1-16                 1785            739557 ns/op            3948 B/op         68 allocs/op
BenchmarkBatchRunGetUsernsFD_Concurrent10-16                 328           4024300 ns/op           39601 B/op        671 allocs/op
PASS
ok      github.com/containerd/containerd/v2/core/mount  3.104s
```

With go1.23 `ptrace`:

```bash
$ go test -bench=.  -benchmem ./ -exec sudo
goos: linux
goarch: amd64
pkg: github.com/containerd/containerd/v2/core/mount
cpu: AMD Ryzen 7 5800H with Radeon Graphics
BenchmarkBatchRunGetUsernsFD_Concurrent1-16                 1815            723252 ns/op            4220 B/op         69 allocs/op
BenchmarkBatchRunGetUsernsFD_Concurrent10-16                 319           3957157 ns/op           42351 B/op        682 allocs/op
PASS
ok      github.com/containerd/containerd/v2/core/mount  3.051s
```

Diff:

The `ptrace` is slower than `go:linkname` mode. However, it's accepctable.

```
goos: linux
goarch: amd64
pkg: github.com/containerd/containerd/v2/core/mount
cpu: AMD Ryzen 7 5800H with Radeon Graphics
                                    │ go122-golinkname │             go122-ptrace              │             go123-ptrace              │
                                    │      sec/op      │    sec/op     vs base                 │    sec/op     vs base                 │
BatchRunGetUsernsFD_Concurrent1-16        533.3µ ± ∞ ¹   739.6µ ± ∞ ¹        ~ (p=1.000 n=1) ²   723.3µ ± ∞ ¹        ~ (p=1.000 n=1) ²
BatchRunGetUsernsFD_Concurrent10-16       3.662m ± ∞ ¹   4.024m ± ∞ ¹        ~ (p=1.000 n=1) ²   3.957m ± ∞ ¹        ~ (p=1.000 n=1) ²
geomean                                   1.397m         1.725m        +23.45%                   1.692m        +21.06%
¹ need >= 6 samples for confidence interval at level 0.95
² need >= 4 samples to detect a difference at alpha level 0.05

                                    │ go122-golinkname │              go122-ptrace               │              go123-ptrace               │
                                    │       B/op       │     B/op       vs base                  │     B/op       vs base                  │
BatchRunGetUsernsFD_Concurrent1-16       1.118Ki ± ∞ ¹   3.855Ki ± ∞ ¹         ~ (p=1.000 n=1) ²   4.121Ki ± ∞ ¹         ~ (p=1.000 n=1) ²
BatchRunGetUsernsFD_Concurrent10-16      11.29Ki ± ∞ ¹   38.67Ki ± ∞ ¹         ~ (p=1.000 n=1) ²   41.36Ki ± ∞ ¹         ~ (p=1.000 n=1) ²
geomean                                  3.553Ki         12.21Ki        +243.65%                   13.06Ki        +267.43%
¹ need >= 6 samples for confidence interval at level 0.95
² need >= 4 samples to detect a difference at alpha level 0.05

                                    │ go122-golinkname │             go122-ptrace             │             go123-ptrace             │
                                    │    allocs/op     │  allocs/op   vs base                 │  allocs/op   vs base                 │
BatchRunGetUsernsFD_Concurrent1-16         43.00 ± ∞ ¹   68.00 ± ∞ ¹        ~ (p=1.000 n=1) ²   69.00 ± ∞ ¹        ~ (p=1.000 n=1) ²
BatchRunGetUsernsFD_Concurrent10-16        421.0 ± ∞ ¹   671.0 ± ∞ ¹        ~ (p=1.000 n=1) ²   682.0 ± ∞ ¹        ~ (p=1.000 n=1) ²
geomean                                    134.5         213.6        +58.76%                   216.9        +61.23%
¹ need >= 6 samples for confidence interval at level 0.95
² need >= 4 samples to detect a difference at alpha level 0.05
```

[1]: <https://github.com/golang/go/issues/67401>
[2]: <https://github.com/golang/go/blob/release-branch.go1.23/src/runtime/proc.go#L4820>

Signed-off-by: Wei Fu <fuweid89@gmail.com>
2024-08-26 21:19:50 +08:00
Sebastiaan van Stijn
9776047243 migrate to github.com/moby/sys/userns
Commit 8437c567d8 migrated the use of the
userns package to the github.com/moby/sys/user module.

After further discussion with maintainers, it was decided to move the
userns package to a separate module, as it has no direct relation with
"user" operations (other than having "user" in its name).

This patch migrates our code to use the new module.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-08 12:48:54 +02:00
Sebastiaan van Stijn
8437c567d8 pkg/userns: deprecate and migrate to github.com/moby/sys/user/userns
The userns package in libcontainer was integrated into the moby/sys/user
module at commit [3778ae603c706494fd1e2c2faf83b406e38d687d][1].

This patch deprecates the containerd fork of that package, and adds it as
an alias for the moby/sys/user/userns package.

[1]: 3778ae603c

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-26 09:47:50 +02:00
Danny Canter
3ea69db8e9 Add helper to ignore eintr
We have quite a few pieces of code laying around containerd
that all loop and ignore eintr as they make syscalls directly
(or use a unix/syscall wrapper) because there's no stdlib
equivalent. This adds a small utility to pkg/sys that we can
use for all of these spots.

Signed-off-by: Danny Canter <danny@dcantah.dev>
2024-04-10 11:16:23 -07:00
Phil Estes
723306d0ed Disable OOM set score unpriv test temporarily
Temporary skip while we find root cause of GHA environment changes
causing failure.

Signed-off-by: Phil Estes <estesp@amazon.com>
2024-03-06 11:38:53 -05:00
Maksym Pavlenko
1ce7b99511 Remove deprecated filesys funcs
Signed-off-by: Maksym Pavlenko <pavlenko.maksym@gmail.com>
2024-02-10 17:55:57 -08:00
Derek McGowan
6be90158cd Move sys to pkg/sys
Signed-off-by: Derek McGowan <derek@mcg.dev>
2024-01-17 09:56:16 -08:00