Skip to content

Commit

Permalink
Merge pull request #24696 from giuseppe/clamp-ulimits-root-no-sys-res…
Browse files Browse the repository at this point in the history
…ource

spec: clamp rlimits without CAP_SYS_RESOURCE
  • Loading branch information
openshift-merge-bot[bot] authored Nov 28, 2024
2 parents a9b163a + 4b38294 commit b965d7b
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions libpod/container_internal_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"slices"
"strconv"
"strings"
"sync"
"syscall"
"time"

Expand Down Expand Up @@ -52,6 +53,7 @@ import (
"github.com/containers/storage/pkg/unshare"
stypes "github.com/containers/storage/types"
securejoin "github.com/cyphar/filepath-securejoin"
"github.com/moby/sys/capability"
runcuser "github.com/moby/sys/user"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
Expand Down Expand Up @@ -177,6 +179,18 @@ func getOverlayUpperAndWorkDir(options []string) (string, string, error) {
return upperDir, workDir, nil
}

// hasCapSysResource returns whether the current process has CAP_SYS_RESOURCE.
var hasCapSysResource = sync.OnceValues(func() (bool, error) {
currentCaps, err := capability.NewPid2(0)
if err != nil {
return false, err
}
if err = currentCaps.Load(); err != nil {
return false, err
}
return currentCaps.Get(capability.EFFECTIVE, capability.CAP_SYS_RESOURCE), nil
})

// Generate spec for a container
// Accepts a map of the container's dependencies
func (c *Container) generateSpec(ctx context.Context) (s *spec.Spec, cleanupFuncRet func(), err error) {
Expand Down Expand Up @@ -678,10 +692,21 @@ func (c *Container) generateSpec(ctx context.Context) (s *spec.Spec, cleanupFunc
nprocSet = true
}
}
needsClamping := false
if !nofileSet || !nprocSet {
needsClamping = isRunningInUserNs
if !needsClamping {
has, err := hasCapSysResource()
if err != nil {
return nil, nil, err
}
needsClamping = !has
}
}
if !nofileSet {
max := rlimT(define.RLimitDefaultValue)
current := rlimT(define.RLimitDefaultValue)
if isRunningInUserNs {
if needsClamping {
var rlimit unix.Rlimit
if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit); err != nil {
logrus.Warnf("Failed to return RLIMIT_NOFILE ulimit %q", err)
Expand All @@ -698,7 +723,7 @@ func (c *Container) generateSpec(ctx context.Context) (s *spec.Spec, cleanupFunc
if !nprocSet {
max := rlimT(define.RLimitDefaultValue)
current := rlimT(define.RLimitDefaultValue)
if isRunningInUserNs {
if needsClamping {
var rlimit unix.Rlimit
if err := unix.Getrlimit(unix.RLIMIT_NPROC, &rlimit); err != nil {
logrus.Warnf("Failed to return RLIMIT_NPROC ulimit %q", err)
Expand Down

0 comments on commit b965d7b

Please sign in to comment.