provider.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package podsecuritypolicy
  14. import (
  15. "fmt"
  16. "strings"
  17. corev1 "k8s.io/api/core/v1"
  18. policy "k8s.io/api/policy/v1beta1"
  19. "k8s.io/apimachinery/pkg/util/validation/field"
  20. utilfeature "k8s.io/apiserver/pkg/util/feature"
  21. api "k8s.io/kubernetes/pkg/apis/core"
  22. "k8s.io/kubernetes/pkg/features"
  23. psputil "k8s.io/kubernetes/pkg/security/podsecuritypolicy/util"
  24. "k8s.io/kubernetes/pkg/securitycontext"
  25. )
  26. // simpleProvider is the default implementation of Provider.
  27. type simpleProvider struct {
  28. psp *policy.PodSecurityPolicy
  29. strategies *ProviderStrategies
  30. }
  31. // ensure we implement the interface correctly.
  32. var _ Provider = &simpleProvider{}
  33. // NewSimpleProvider creates a new Provider instance.
  34. func NewSimpleProvider(psp *policy.PodSecurityPolicy, namespace string, strategyFactory StrategyFactory) (Provider, error) {
  35. if psp == nil {
  36. return nil, fmt.Errorf("NewSimpleProvider requires a PodSecurityPolicy")
  37. }
  38. if strategyFactory == nil {
  39. return nil, fmt.Errorf("NewSimpleProvider requires a StrategyFactory")
  40. }
  41. strategies, err := strategyFactory.CreateStrategies(psp, namespace)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return &simpleProvider{
  46. psp: psp,
  47. strategies: strategies,
  48. }, nil
  49. }
  50. // MutatePod sets the default values of the required but not filled fields.
  51. // Validation should be used after the context is defaulted to ensure it
  52. // complies with the required restrictions.
  53. func (s *simpleProvider) MutatePod(pod *api.Pod) error {
  54. sc := securitycontext.NewPodSecurityContextMutator(pod.Spec.SecurityContext)
  55. if sc.SupplementalGroups() == nil {
  56. supGroups, err := s.strategies.SupplementalGroupStrategy.Generate(pod)
  57. if err != nil {
  58. return err
  59. }
  60. sc.SetSupplementalGroups(supGroups)
  61. }
  62. if sc.FSGroup() == nil {
  63. fsGroup, err := s.strategies.FSGroupStrategy.GenerateSingle(pod)
  64. if err != nil {
  65. return err
  66. }
  67. sc.SetFSGroup(fsGroup)
  68. }
  69. if sc.SELinuxOptions() == nil {
  70. seLinux, err := s.strategies.SELinuxStrategy.Generate(pod, nil)
  71. if err != nil {
  72. return err
  73. }
  74. sc.SetSELinuxOptions(seLinux)
  75. }
  76. // This is only generated on the pod level. Containers inherit the pod's profile. If the
  77. // container has a specific profile set then it will be caught in the validation step.
  78. seccompProfile, err := s.strategies.SeccompStrategy.Generate(pod.Annotations, pod)
  79. if err != nil {
  80. return err
  81. }
  82. if seccompProfile != "" {
  83. if pod.Annotations == nil {
  84. pod.Annotations = map[string]string{}
  85. }
  86. pod.Annotations[api.SeccompPodAnnotationKey] = seccompProfile
  87. }
  88. pod.Spec.SecurityContext = sc.PodSecurityContext()
  89. if s.psp.Spec.RuntimeClass != nil && pod.Spec.RuntimeClassName == nil {
  90. pod.Spec.RuntimeClassName = s.psp.Spec.RuntimeClass.DefaultRuntimeClassName
  91. }
  92. for i := range pod.Spec.InitContainers {
  93. if err := s.mutateContainer(pod, &pod.Spec.InitContainers[i]); err != nil {
  94. return err
  95. }
  96. }
  97. for i := range pod.Spec.Containers {
  98. if err := s.mutateContainer(pod, &pod.Spec.Containers[i]); err != nil {
  99. return err
  100. }
  101. }
  102. return nil
  103. }
  104. // mutateContainer sets the default values of the required but not filled fields.
  105. // It modifies the SecurityContext of the container and annotations of the pod. Validation should
  106. // be used after the context is defaulted to ensure it complies with the required restrictions.
  107. func (s *simpleProvider) mutateContainer(pod *api.Pod, container *api.Container) error {
  108. sc := securitycontext.NewEffectiveContainerSecurityContextMutator(
  109. securitycontext.NewPodSecurityContextAccessor(pod.Spec.SecurityContext),
  110. securitycontext.NewContainerSecurityContextMutator(container.SecurityContext),
  111. )
  112. if sc.RunAsUser() == nil {
  113. uid, err := s.strategies.RunAsUserStrategy.Generate(pod, container)
  114. if err != nil {
  115. return err
  116. }
  117. sc.SetRunAsUser(uid)
  118. }
  119. if utilfeature.DefaultFeatureGate.Enabled(features.RunAsGroup) {
  120. if sc.RunAsGroup() == nil {
  121. gid, err := s.strategies.RunAsGroupStrategy.GenerateSingle(pod)
  122. if err != nil {
  123. return err
  124. }
  125. sc.SetRunAsGroup(gid)
  126. }
  127. }
  128. if sc.SELinuxOptions() == nil {
  129. seLinux, err := s.strategies.SELinuxStrategy.Generate(pod, container)
  130. if err != nil {
  131. return err
  132. }
  133. sc.SetSELinuxOptions(seLinux)
  134. }
  135. annotations, err := s.strategies.AppArmorStrategy.Generate(pod.Annotations, container)
  136. if err != nil {
  137. return err
  138. }
  139. // if we're using the non-root strategy set the marker that this container should not be
  140. // run as root which will signal to the kubelet to do a final check either on the runAsUser
  141. // or, if runAsUser is not set, the image UID will be checked.
  142. if sc.RunAsNonRoot() == nil && sc.RunAsUser() == nil && s.psp.Spec.RunAsUser.Rule == policy.RunAsUserStrategyMustRunAsNonRoot {
  143. nonRoot := true
  144. sc.SetRunAsNonRoot(&nonRoot)
  145. }
  146. caps, err := s.strategies.CapabilitiesStrategy.Generate(pod, container)
  147. if err != nil {
  148. return err
  149. }
  150. sc.SetCapabilities(caps)
  151. // if the PSP requires a read only root filesystem and the container has not made a specific
  152. // request then default ReadOnlyRootFilesystem to true.
  153. if s.psp.Spec.ReadOnlyRootFilesystem && sc.ReadOnlyRootFilesystem() == nil {
  154. readOnlyRootFS := true
  155. sc.SetReadOnlyRootFilesystem(&readOnlyRootFS)
  156. }
  157. // if the PSP sets DefaultAllowPrivilegeEscalation and the container security context
  158. // allowPrivilegeEscalation is not set, then default to that set by the PSP.
  159. if s.psp.Spec.DefaultAllowPrivilegeEscalation != nil && sc.AllowPrivilegeEscalation() == nil {
  160. sc.SetAllowPrivilegeEscalation(s.psp.Spec.DefaultAllowPrivilegeEscalation)
  161. }
  162. // if the PSP sets psp.AllowPrivilegeEscalation to false, set that as the default
  163. if !*s.psp.Spec.AllowPrivilegeEscalation && sc.AllowPrivilegeEscalation() == nil {
  164. sc.SetAllowPrivilegeEscalation(s.psp.Spec.AllowPrivilegeEscalation)
  165. }
  166. pod.Annotations = annotations
  167. container.SecurityContext = sc.ContainerSecurityContext()
  168. return nil
  169. }
  170. // ValidatePod ensure a pod is in compliance with the given constraints.
  171. func (s *simpleProvider) ValidatePod(pod *api.Pod) field.ErrorList {
  172. allErrs := field.ErrorList{}
  173. sc := securitycontext.NewPodSecurityContextAccessor(pod.Spec.SecurityContext)
  174. scPath := field.NewPath("spec", "securityContext")
  175. var fsGroups []int64
  176. if fsGroup := sc.FSGroup(); fsGroup != nil {
  177. fsGroups = []int64{*fsGroup}
  178. }
  179. allErrs = append(allErrs, s.strategies.FSGroupStrategy.Validate(scPath.Child("fsGroup"), pod, fsGroups)...)
  180. allErrs = append(allErrs, s.strategies.SupplementalGroupStrategy.Validate(scPath.Child("supplementalGroups"), pod, sc.SupplementalGroups())...)
  181. allErrs = append(allErrs, s.strategies.SeccompStrategy.ValidatePod(pod)...)
  182. allErrs = append(allErrs, s.strategies.SELinuxStrategy.Validate(scPath.Child("seLinuxOptions"), pod, nil, sc.SELinuxOptions())...)
  183. if !s.psp.Spec.HostNetwork && sc.HostNetwork() {
  184. allErrs = append(allErrs, field.Invalid(scPath.Child("hostNetwork"), sc.HostNetwork(), "Host network is not allowed to be used"))
  185. }
  186. if !s.psp.Spec.HostPID && sc.HostPID() {
  187. allErrs = append(allErrs, field.Invalid(scPath.Child("hostPID"), sc.HostPID(), "Host PID is not allowed to be used"))
  188. }
  189. if !s.psp.Spec.HostIPC && sc.HostIPC() {
  190. allErrs = append(allErrs, field.Invalid(scPath.Child("hostIPC"), sc.HostIPC(), "Host IPC is not allowed to be used"))
  191. }
  192. allErrs = append(allErrs, s.strategies.SysctlsStrategy.Validate(pod)...)
  193. allErrs = append(allErrs, s.validatePodVolumes(pod)...)
  194. if s.psp.Spec.RuntimeClass != nil {
  195. allErrs = append(allErrs, validateRuntimeClassName(pod.Spec.RuntimeClassName, s.psp.Spec.RuntimeClass.AllowedRuntimeClassNames)...)
  196. }
  197. fldPath := field.NewPath("spec", "initContainers")
  198. for i := range pod.Spec.InitContainers {
  199. allErrs = append(allErrs, s.validateContainer(pod, &pod.Spec.InitContainers[i], fldPath.Index(i))...)
  200. }
  201. fldPath = field.NewPath("spec", "containers")
  202. for i := range pod.Spec.Containers {
  203. allErrs = append(allErrs, s.validateContainer(pod, &pod.Spec.Containers[i], fldPath.Index(i))...)
  204. }
  205. return allErrs
  206. }
  207. func (s *simpleProvider) validatePodVolumes(pod *api.Pod) field.ErrorList {
  208. allErrs := field.ErrorList{}
  209. if len(pod.Spec.Volumes) > 0 {
  210. allowsAllVolumeTypes := psputil.PSPAllowsAllVolumes(s.psp)
  211. allowedVolumes := psputil.FSTypeToStringSet(s.psp.Spec.Volumes)
  212. for i, v := range pod.Spec.Volumes {
  213. fsType, err := psputil.GetVolumeFSType(v)
  214. if err != nil {
  215. allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "volumes").Index(i), string(fsType), err.Error()))
  216. continue
  217. }
  218. if !allowsAllVolumeTypes && !allowedVolumes.Has(string(fsType)) {
  219. allErrs = append(allErrs, field.Invalid(
  220. field.NewPath("spec", "volumes").Index(i), string(fsType),
  221. fmt.Sprintf("%s volumes are not allowed to be used", string(fsType))))
  222. continue
  223. }
  224. switch fsType {
  225. case policy.HostPath:
  226. allows, mustBeReadOnly := psputil.AllowsHostVolumePath(s.psp, v.HostPath.Path)
  227. if !allows {
  228. allErrs = append(allErrs, field.Invalid(
  229. field.NewPath("spec", "volumes").Index(i).Child("hostPath", "pathPrefix"), v.HostPath.Path,
  230. fmt.Sprintf("is not allowed to be used")))
  231. } else if mustBeReadOnly {
  232. // Ensure all the VolumeMounts that use this volume are read-only
  233. for i, c := range pod.Spec.InitContainers {
  234. for j, cv := range c.VolumeMounts {
  235. if cv.Name == v.Name && !cv.ReadOnly {
  236. allErrs = append(allErrs, field.Invalid(
  237. field.NewPath("spec", "initContainers").Index(i).Child("volumeMounts").Index(j).Child("readOnly"),
  238. cv.ReadOnly, "must be read-only"),
  239. )
  240. }
  241. }
  242. }
  243. for i, c := range pod.Spec.Containers {
  244. for j, cv := range c.VolumeMounts {
  245. if cv.Name == v.Name && !cv.ReadOnly {
  246. allErrs = append(allErrs, field.Invalid(
  247. field.NewPath("spec", "containers").Index(i).Child("volumeMounts").Index(j).Child("readOnly"),
  248. cv.ReadOnly, "must be read-only"),
  249. )
  250. }
  251. }
  252. }
  253. }
  254. case policy.FlexVolume:
  255. if len(s.psp.Spec.AllowedFlexVolumes) > 0 {
  256. found := false
  257. driver := v.FlexVolume.Driver
  258. for _, allowedFlexVolume := range s.psp.Spec.AllowedFlexVolumes {
  259. if driver == allowedFlexVolume.Driver {
  260. found = true
  261. break
  262. }
  263. }
  264. if !found {
  265. allErrs = append(allErrs,
  266. field.Invalid(field.NewPath("spec", "volumes").Index(i).Child("driver"), driver,
  267. "Flexvolume driver is not allowed to be used"))
  268. }
  269. }
  270. case policy.CSI:
  271. if utilfeature.DefaultFeatureGate.Enabled(features.CSIInlineVolume) {
  272. if len(s.psp.Spec.AllowedCSIDrivers) > 0 {
  273. found := false
  274. driver := v.CSI.Driver
  275. for _, allowedCSIDriver := range s.psp.Spec.AllowedCSIDrivers {
  276. if driver == allowedCSIDriver.Name {
  277. found = true
  278. break
  279. }
  280. }
  281. if !found {
  282. allErrs = append(allErrs,
  283. field.Invalid(field.NewPath("spec", "volumes").Index(i).Child("csi", "driver"), driver,
  284. "Inline CSI driver is not allowed to be used"))
  285. }
  286. }
  287. }
  288. }
  289. }
  290. }
  291. return allErrs
  292. }
  293. // Ensure a container's SecurityContext is in compliance with the given constraints
  294. func (s *simpleProvider) validateContainer(pod *api.Pod, container *api.Container, containerPath *field.Path) field.ErrorList {
  295. allErrs := field.ErrorList{}
  296. podSC := securitycontext.NewPodSecurityContextAccessor(pod.Spec.SecurityContext)
  297. sc := securitycontext.NewEffectiveContainerSecurityContextAccessor(podSC, securitycontext.NewContainerSecurityContextMutator(container.SecurityContext))
  298. scPath := containerPath.Child("securityContext")
  299. allErrs = append(allErrs, s.strategies.RunAsUserStrategy.Validate(scPath, pod, container, sc.RunAsNonRoot(), sc.RunAsUser())...)
  300. if utilfeature.DefaultFeatureGate.Enabled(features.RunAsGroup) {
  301. var runAsGroups []int64
  302. if sc.RunAsGroup() != nil {
  303. runAsGroups = []int64{*sc.RunAsGroup()}
  304. }
  305. allErrs = append(allErrs, s.strategies.RunAsGroupStrategy.Validate(scPath, pod, runAsGroups)...)
  306. }
  307. allErrs = append(allErrs, s.strategies.SELinuxStrategy.Validate(scPath.Child("seLinuxOptions"), pod, container, sc.SELinuxOptions())...)
  308. allErrs = append(allErrs, s.strategies.AppArmorStrategy.Validate(pod, container)...)
  309. allErrs = append(allErrs, s.strategies.SeccompStrategy.ValidateContainer(pod, container)...)
  310. privileged := sc.Privileged()
  311. if !s.psp.Spec.Privileged && privileged != nil && *privileged {
  312. allErrs = append(allErrs, field.Invalid(scPath.Child("privileged"), *privileged, "Privileged containers are not allowed"))
  313. }
  314. procMount := sc.ProcMount()
  315. allowedProcMounts := s.psp.Spec.AllowedProcMountTypes
  316. if len(allowedProcMounts) == 0 {
  317. allowedProcMounts = []corev1.ProcMountType{corev1.DefaultProcMount}
  318. }
  319. foundProcMountType := false
  320. for _, pm := range allowedProcMounts {
  321. if string(pm) == string(procMount) {
  322. foundProcMountType = true
  323. }
  324. }
  325. if !foundProcMountType {
  326. allErrs = append(allErrs, field.Invalid(scPath.Child("procMount"), procMount, "ProcMountType is not allowed"))
  327. }
  328. allErrs = append(allErrs, s.strategies.CapabilitiesStrategy.Validate(scPath.Child("capabilities"), pod, container, sc.Capabilities())...)
  329. allErrs = append(allErrs, s.hasInvalidHostPort(container, containerPath)...)
  330. if s.psp.Spec.ReadOnlyRootFilesystem {
  331. readOnly := sc.ReadOnlyRootFilesystem()
  332. if readOnly == nil {
  333. allErrs = append(allErrs, field.Invalid(scPath.Child("readOnlyRootFilesystem"), readOnly, "ReadOnlyRootFilesystem may not be nil and must be set to true"))
  334. } else if !*readOnly {
  335. allErrs = append(allErrs, field.Invalid(scPath.Child("readOnlyRootFilesystem"), *readOnly, "ReadOnlyRootFilesystem must be set to true"))
  336. }
  337. }
  338. allowEscalation := sc.AllowPrivilegeEscalation()
  339. if !*s.psp.Spec.AllowPrivilegeEscalation && (allowEscalation == nil || *allowEscalation) {
  340. allErrs = append(allErrs, field.Invalid(scPath.Child("allowPrivilegeEscalation"), allowEscalation, "Allowing privilege escalation for containers is not allowed"))
  341. }
  342. return allErrs
  343. }
  344. // hasInvalidHostPort checks whether the port definitions on the container fall outside of the ranges allowed by the PSP.
  345. func (s *simpleProvider) hasInvalidHostPort(container *api.Container, fldPath *field.Path) field.ErrorList {
  346. allErrs := field.ErrorList{}
  347. for _, cp := range container.Ports {
  348. if cp.HostPort > 0 && !s.isValidHostPort(cp.HostPort) {
  349. detail := fmt.Sprintf("Host port %d is not allowed to be used. Allowed ports: [%s]", cp.HostPort, hostPortRangesToString(s.psp.Spec.HostPorts))
  350. allErrs = append(allErrs, field.Invalid(fldPath.Child("hostPort"), cp.HostPort, detail))
  351. }
  352. }
  353. return allErrs
  354. }
  355. // isValidHostPort returns true if the port falls in any range allowed by the PSP.
  356. func (s *simpleProvider) isValidHostPort(port int32) bool {
  357. for _, hostPortRange := range s.psp.Spec.HostPorts {
  358. if port >= hostPortRange.Min && port <= hostPortRange.Max {
  359. return true
  360. }
  361. }
  362. return false
  363. }
  364. // Get the name of the PSP that this provider was initialized with.
  365. func (s *simpleProvider) GetPSPName() string {
  366. return s.psp.Name
  367. }
  368. func hostPortRangesToString(ranges []policy.HostPortRange) string {
  369. formattedString := ""
  370. if ranges != nil {
  371. strRanges := []string{}
  372. for _, r := range ranges {
  373. if r.Min == r.Max {
  374. strRanges = append(strRanges, fmt.Sprintf("%d", r.Min))
  375. } else {
  376. strRanges = append(strRanges, fmt.Sprintf("%d-%d", r.Min, r.Max))
  377. }
  378. }
  379. formattedString = strings.Join(strRanges, ",")
  380. }
  381. return formattedString
  382. }
  383. // validates that the actual RuntimeClassName is contained in the list of valid names.
  384. func validateRuntimeClassName(actual *string, validNames []string) field.ErrorList {
  385. if actual == nil {
  386. return nil // An unset RuntimeClassName is always allowed.
  387. }
  388. for _, valid := range validNames {
  389. if valid == policy.AllowAllRuntimeClassNames {
  390. return nil
  391. }
  392. if *actual == valid {
  393. return nil
  394. }
  395. }
  396. return field.ErrorList{field.Invalid(field.NewPath("spec", "runtimeClassName"), *actual, "")}
  397. }