psp.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. /*
  2. Copyright 2017 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 framework
  14. import (
  15. "context"
  16. "fmt"
  17. "sync"
  18. v1 "k8s.io/api/core/v1"
  19. policyv1beta1 "k8s.io/api/policy/v1beta1"
  20. rbacv1 "k8s.io/api/rbac/v1"
  21. apierrors "k8s.io/apimachinery/pkg/api/errors"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/runtime/schema"
  24. "k8s.io/apiserver/pkg/authentication/serviceaccount"
  25. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/kubernetes/pkg/security/podsecuritypolicy/seccomp"
  27. "github.com/onsi/ginkgo"
  28. // TODO: Remove the following imports (ref: https://github.com/kubernetes/kubernetes/issues/81245)
  29. "k8s.io/kubernetes/test/e2e/framework/auth"
  30. )
  31. const (
  32. podSecurityPolicyPrivileged = "e2e-test-privileged-psp"
  33. )
  34. var (
  35. isPSPEnabledOnce sync.Once
  36. isPSPEnabled bool
  37. )
  38. // privilegedPSP creates a PodSecurityPolicy that allows everything.
  39. func privilegedPSP(name string) *policyv1beta1.PodSecurityPolicy {
  40. allowPrivilegeEscalation := true
  41. return &policyv1beta1.PodSecurityPolicy{
  42. ObjectMeta: metav1.ObjectMeta{
  43. Name: name,
  44. Annotations: map[string]string{seccomp.AllowedProfilesAnnotationKey: seccomp.AllowAny},
  45. },
  46. Spec: policyv1beta1.PodSecurityPolicySpec{
  47. Privileged: true,
  48. AllowPrivilegeEscalation: &allowPrivilegeEscalation,
  49. AllowedCapabilities: []v1.Capability{"*"},
  50. Volumes: []policyv1beta1.FSType{policyv1beta1.All},
  51. HostNetwork: true,
  52. HostPorts: []policyv1beta1.HostPortRange{{Min: 0, Max: 65535}},
  53. HostIPC: true,
  54. HostPID: true,
  55. RunAsUser: policyv1beta1.RunAsUserStrategyOptions{
  56. Rule: policyv1beta1.RunAsUserStrategyRunAsAny,
  57. },
  58. SELinux: policyv1beta1.SELinuxStrategyOptions{
  59. Rule: policyv1beta1.SELinuxStrategyRunAsAny,
  60. },
  61. SupplementalGroups: policyv1beta1.SupplementalGroupsStrategyOptions{
  62. Rule: policyv1beta1.SupplementalGroupsStrategyRunAsAny,
  63. },
  64. FSGroup: policyv1beta1.FSGroupStrategyOptions{
  65. Rule: policyv1beta1.FSGroupStrategyRunAsAny,
  66. },
  67. ReadOnlyRootFilesystem: false,
  68. AllowedUnsafeSysctls: []string{"*"},
  69. },
  70. }
  71. }
  72. // IsPodSecurityPolicyEnabled returns true if PodSecurityPolicy is enabled. Otherwise false.
  73. func IsPodSecurityPolicyEnabled(kubeClient clientset.Interface) bool {
  74. isPSPEnabledOnce.Do(func() {
  75. psps, err := kubeClient.PolicyV1beta1().PodSecurityPolicies().List(context.TODO(), metav1.ListOptions{})
  76. if err != nil {
  77. Logf("Error listing PodSecurityPolicies; assuming PodSecurityPolicy is disabled: %v", err)
  78. isPSPEnabled = false
  79. } else if psps == nil || len(psps.Items) == 0 {
  80. Logf("No PodSecurityPolicies found; assuming PodSecurityPolicy is disabled.")
  81. isPSPEnabled = false
  82. } else {
  83. Logf("Found PodSecurityPolicies; assuming PodSecurityPolicy is enabled.")
  84. isPSPEnabled = true
  85. }
  86. })
  87. return isPSPEnabled
  88. }
  89. var (
  90. privilegedPSPOnce sync.Once
  91. )
  92. // CreatePrivilegedPSPBinding creates the privileged PSP & role
  93. func CreatePrivilegedPSPBinding(kubeClient clientset.Interface, namespace string) {
  94. if !IsPodSecurityPolicyEnabled(kubeClient) {
  95. return
  96. }
  97. // Create the privileged PSP & role
  98. privilegedPSPOnce.Do(func() {
  99. _, err := kubeClient.PolicyV1beta1().PodSecurityPolicies().Get(context.TODO(), podSecurityPolicyPrivileged, metav1.GetOptions{})
  100. if !apierrors.IsNotFound(err) {
  101. // Privileged PSP was already created.
  102. ExpectNoError(err, "Failed to get PodSecurityPolicy %s", podSecurityPolicyPrivileged)
  103. return
  104. }
  105. psp := privilegedPSP(podSecurityPolicyPrivileged)
  106. _, err = kubeClient.PolicyV1beta1().PodSecurityPolicies().Create(context.TODO(), psp, metav1.CreateOptions{})
  107. if !apierrors.IsAlreadyExists(err) {
  108. ExpectNoError(err, "Failed to create PSP %s", podSecurityPolicyPrivileged)
  109. }
  110. if auth.IsRBACEnabled(kubeClient.RbacV1()) {
  111. // Create the Role to bind it to the namespace.
  112. _, err = kubeClient.RbacV1().ClusterRoles().Create(context.TODO(), &rbacv1.ClusterRole{
  113. ObjectMeta: metav1.ObjectMeta{Name: podSecurityPolicyPrivileged},
  114. Rules: []rbacv1.PolicyRule{{
  115. APIGroups: []string{"extensions"},
  116. Resources: []string{"podsecuritypolicies"},
  117. ResourceNames: []string{podSecurityPolicyPrivileged},
  118. Verbs: []string{"use"},
  119. }},
  120. }, metav1.CreateOptions{})
  121. if !apierrors.IsAlreadyExists(err) {
  122. ExpectNoError(err, "Failed to create PSP role")
  123. }
  124. }
  125. })
  126. if auth.IsRBACEnabled(kubeClient.RbacV1()) {
  127. ginkgo.By(fmt.Sprintf("Binding the %s PodSecurityPolicy to the default service account in %s",
  128. podSecurityPolicyPrivileged, namespace))
  129. err := auth.BindClusterRoleInNamespace(kubeClient.RbacV1(),
  130. podSecurityPolicyPrivileged,
  131. namespace,
  132. rbacv1.Subject{
  133. Kind: rbacv1.ServiceAccountKind,
  134. Namespace: namespace,
  135. Name: "default",
  136. })
  137. ExpectNoError(err)
  138. ExpectNoError(auth.WaitForNamedAuthorizationUpdate(kubeClient.AuthorizationV1(),
  139. serviceaccount.MakeUsername(namespace, "default"), namespace, "use", podSecurityPolicyPrivileged,
  140. schema.GroupResource{Group: "extensions", Resource: "podsecuritypolicies"}, true))
  141. }
  142. }