k8s.io/kubernetes@v1.29.3/pkg/kubelet/kuberuntime/security_context_others.go (about) 1 //go:build !windows 2 // +build !windows 3 4 /* 5 Copyright 2020 The Kubernetes Authors. 6 7 Licensed under the Apache License, Version 2.0 (the "License"); 8 you may not use this file except in compliance with the License. 9 You may obtain a copy of the License at 10 11 http://www.apache.org/licenses/LICENSE-2.0 12 13 Unless required by applicable law or agreed to in writing, software 14 distributed under the License is distributed on an "AS IS" BASIS, 15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 See the License for the specific language governing permissions and 17 limitations under the License. 18 */ 19 20 package kuberuntime 21 22 import ( 23 "fmt" 24 25 "k8s.io/api/core/v1" 26 "k8s.io/kubernetes/pkg/kubelet/util/format" 27 "k8s.io/kubernetes/pkg/securitycontext" 28 ) 29 30 // verifyRunAsNonRoot verifies RunAsNonRoot. 31 func verifyRunAsNonRoot(pod *v1.Pod, container *v1.Container, uid *int64, username string) error { 32 effectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container) 33 // If the option is not set, or if running as root is allowed, return nil. 34 if effectiveSc == nil || effectiveSc.RunAsNonRoot == nil || !*effectiveSc.RunAsNonRoot { 35 return nil 36 } 37 38 if effectiveSc.RunAsUser != nil { 39 if *effectiveSc.RunAsUser == 0 { 40 return fmt.Errorf("container's runAsUser breaks non-root policy (pod: %q, container: %s)", format.Pod(pod), container.Name) 41 } 42 return nil 43 } 44 45 switch { 46 case uid != nil && *uid == 0: 47 return fmt.Errorf("container has runAsNonRoot and image will run as root (pod: %q, container: %s)", format.Pod(pod), container.Name) 48 case uid == nil && len(username) > 0: 49 return fmt.Errorf("container has runAsNonRoot and image has non-numeric user (%s), cannot verify user is non-root (pod: %q, container: %s)", username, format.Pod(pod), container.Name) 50 default: 51 return nil 52 } 53 }