security_context.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. Copyright 2015 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. /* This test check that SecurityContext parameters specified at the
  14. * pod or the container level work as intended. These tests cannot be
  15. * run when the 'SecurityContextDeny' admission controller is not used
  16. * so they are skipped by default.
  17. */
  18. package node
  19. import (
  20. "context"
  21. "fmt"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/util/uuid"
  25. "k8s.io/kubernetes/test/e2e/framework"
  26. e2ekubectl "k8s.io/kubernetes/test/e2e/framework/kubectl"
  27. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  28. imageutils "k8s.io/kubernetes/test/utils/image"
  29. "github.com/onsi/ginkgo"
  30. "github.com/onsi/gomega"
  31. )
  32. func scTestPod(hostIPC bool, hostPID bool) *v1.Pod {
  33. podName := "security-context-" + string(uuid.NewUUID())
  34. pod := &v1.Pod{
  35. ObjectMeta: metav1.ObjectMeta{
  36. Name: podName,
  37. Labels: map[string]string{"name": podName},
  38. Annotations: map[string]string{},
  39. },
  40. Spec: v1.PodSpec{
  41. HostIPC: hostIPC,
  42. HostPID: hostPID,
  43. SecurityContext: &v1.PodSecurityContext{},
  44. Containers: []v1.Container{
  45. {
  46. Name: "test-container",
  47. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  48. },
  49. },
  50. RestartPolicy: v1.RestartPolicyNever,
  51. },
  52. }
  53. return pod
  54. }
  55. var _ = SIGDescribe("Security Context", func() {
  56. f := framework.NewDefaultFramework("security-context")
  57. ginkgo.It("should support pod.Spec.SecurityContext.SupplementalGroups [LinuxOnly]", func() {
  58. pod := scTestPod(false, false)
  59. pod.Spec.Containers[0].Command = []string{"id", "-G"}
  60. pod.Spec.SecurityContext.SupplementalGroups = []int64{1234, 5678}
  61. groups := []string{"1234", "5678"}
  62. f.TestContainerOutput("pod.Spec.SecurityContext.SupplementalGroups", pod, 0, groups)
  63. })
  64. ginkgo.It("should support pod.Spec.SecurityContext.RunAsUser [LinuxOnly]", func() {
  65. pod := scTestPod(false, false)
  66. userID := int64(1001)
  67. pod.Spec.SecurityContext.RunAsUser = &userID
  68. pod.Spec.Containers[0].Command = []string{"sh", "-c", "id"}
  69. f.TestContainerOutput("pod.Spec.SecurityContext.RunAsUser", pod, 0, []string{
  70. fmt.Sprintf("uid=%v", userID),
  71. fmt.Sprintf("gid=%v", 0),
  72. })
  73. })
  74. ginkgo.It("should support pod.Spec.SecurityContext.RunAsUser And pod.Spec.SecurityContext.RunAsGroup [LinuxOnly]", func() {
  75. pod := scTestPod(false, false)
  76. userID := int64(1001)
  77. groupID := int64(2002)
  78. pod.Spec.SecurityContext.RunAsUser = &userID
  79. pod.Spec.SecurityContext.RunAsGroup = &groupID
  80. pod.Spec.Containers[0].Command = []string{"sh", "-c", "id"}
  81. f.TestContainerOutput("pod.Spec.SecurityContext.RunAsUser", pod, 0, []string{
  82. fmt.Sprintf("uid=%v", userID),
  83. fmt.Sprintf("gid=%v", groupID),
  84. })
  85. })
  86. ginkgo.It("should support container.SecurityContext.RunAsUser [LinuxOnly]", func() {
  87. pod := scTestPod(false, false)
  88. userID := int64(1001)
  89. overrideUserID := int64(1002)
  90. pod.Spec.SecurityContext.RunAsUser = &userID
  91. pod.Spec.Containers[0].SecurityContext = new(v1.SecurityContext)
  92. pod.Spec.Containers[0].SecurityContext.RunAsUser = &overrideUserID
  93. pod.Spec.Containers[0].Command = []string{"sh", "-c", "id"}
  94. f.TestContainerOutput("pod.Spec.SecurityContext.RunAsUser", pod, 0, []string{
  95. fmt.Sprintf("uid=%v", overrideUserID),
  96. fmt.Sprintf("gid=%v", 0),
  97. })
  98. })
  99. ginkgo.It("should support container.SecurityContext.RunAsUser And container.SecurityContext.RunAsGroup [LinuxOnly]", func() {
  100. pod := scTestPod(false, false)
  101. userID := int64(1001)
  102. groupID := int64(2001)
  103. overrideUserID := int64(1002)
  104. overrideGroupID := int64(2002)
  105. pod.Spec.SecurityContext.RunAsUser = &userID
  106. pod.Spec.SecurityContext.RunAsGroup = &groupID
  107. pod.Spec.Containers[0].SecurityContext = new(v1.SecurityContext)
  108. pod.Spec.Containers[0].SecurityContext.RunAsUser = &overrideUserID
  109. pod.Spec.Containers[0].SecurityContext.RunAsGroup = &overrideGroupID
  110. pod.Spec.Containers[0].Command = []string{"sh", "-c", "id"}
  111. f.TestContainerOutput("pod.Spec.SecurityContext.RunAsUser", pod, 0, []string{
  112. fmt.Sprintf("uid=%v", overrideUserID),
  113. fmt.Sprintf("gid=%v", overrideGroupID),
  114. })
  115. })
  116. ginkgo.It("should support volume SELinux relabeling [Flaky] [LinuxOnly]", func() {
  117. testPodSELinuxLabeling(f, false, false)
  118. })
  119. ginkgo.It("should support volume SELinux relabeling when using hostIPC [Flaky] [LinuxOnly]", func() {
  120. testPodSELinuxLabeling(f, true, false)
  121. })
  122. ginkgo.It("should support volume SELinux relabeling when using hostPID [Flaky] [LinuxOnly]", func() {
  123. testPodSELinuxLabeling(f, false, true)
  124. })
  125. ginkgo.It("should support seccomp alpha unconfined annotation on the container [Feature:Seccomp] [LinuxOnly]", func() {
  126. // TODO: port to SecurityContext as soon as seccomp is out of alpha
  127. pod := scTestPod(false, false)
  128. pod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+"test-container"] = "unconfined"
  129. pod.Annotations[v1.SeccompPodAnnotationKey] = v1.SeccompProfileRuntimeDefault
  130. pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"}
  131. f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled
  132. })
  133. ginkgo.It("should support seccomp alpha unconfined annotation on the pod [Feature:Seccomp] [LinuxOnly]", func() {
  134. // TODO: port to SecurityContext as soon as seccomp is out of alpha
  135. pod := scTestPod(false, false)
  136. pod.Annotations[v1.SeccompPodAnnotationKey] = "unconfined"
  137. pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"}
  138. f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled
  139. })
  140. ginkgo.It("should support seccomp alpha runtime/default annotation [Feature:Seccomp] [LinuxOnly]", func() {
  141. // TODO: port to SecurityContext as soon as seccomp is out of alpha
  142. pod := scTestPod(false, false)
  143. pod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+"test-container"] = v1.SeccompProfileRuntimeDefault
  144. pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"}
  145. f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"2"}) // seccomp filtered
  146. })
  147. ginkgo.It("should support seccomp default which is unconfined [Feature:Seccomp] [LinuxOnly]", func() {
  148. // TODO: port to SecurityContext as soon as seccomp is out of alpha
  149. pod := scTestPod(false, false)
  150. pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"}
  151. f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled
  152. })
  153. })
  154. func testPodSELinuxLabeling(f *framework.Framework, hostIPC bool, hostPID bool) {
  155. // Write and read a file with an empty_dir volume
  156. // with a pod with the MCS label s0:c0,c1
  157. pod := scTestPod(hostIPC, hostPID)
  158. volumeName := "test-volume"
  159. mountPath := "/mounted_volume"
  160. pod.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{
  161. {
  162. Name: volumeName,
  163. MountPath: mountPath,
  164. },
  165. }
  166. pod.Spec.Volumes = []v1.Volume{
  167. {
  168. Name: volumeName,
  169. VolumeSource: v1.VolumeSource{
  170. EmptyDir: &v1.EmptyDirVolumeSource{
  171. Medium: v1.StorageMediumDefault,
  172. },
  173. },
  174. },
  175. }
  176. pod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{
  177. Level: "s0:c0,c1",
  178. }
  179. pod.Spec.Containers[0].Command = []string{"sleep", "6000"}
  180. client := f.ClientSet.CoreV1().Pods(f.Namespace.Name)
  181. pod, err := client.Create(context.TODO(), pod, metav1.CreateOptions{})
  182. framework.ExpectNoError(err, "Error creating pod %v", pod)
  183. framework.ExpectNoError(e2epod.WaitForPodRunningInNamespace(f.ClientSet, pod))
  184. testContent := "hello"
  185. testFilePath := mountPath + "/TEST"
  186. tk := e2ekubectl.NewTestKubeconfig(framework.TestContext.CertDir, framework.TestContext.Host, framework.TestContext.KubeConfig, framework.TestContext.KubeContext, framework.TestContext.KubectlPath, f.Namespace.Name)
  187. err = tk.WriteFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, testFilePath, testContent)
  188. framework.ExpectNoError(err)
  189. content, err := tk.ReadFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, testFilePath)
  190. framework.ExpectNoError(err)
  191. gomega.Expect(content).To(gomega.ContainSubstring(testContent))
  192. foundPod, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  193. framework.ExpectNoError(err)
  194. // Confirm that the file can be accessed from a second
  195. // pod using host_path with the same MCS label
  196. volumeHostPath := fmt.Sprintf("%s/pods/%s/volumes/kubernetes.io~empty-dir/%s", framework.TestContext.KubeVolumeDir, foundPod.UID, volumeName)
  197. ginkgo.By(fmt.Sprintf("confirming a container with the same label can read the file under --volume-dir=%s", framework.TestContext.KubeVolumeDir))
  198. pod = scTestPod(hostIPC, hostPID)
  199. pod.Spec.NodeName = foundPod.Spec.NodeName
  200. volumeMounts := []v1.VolumeMount{
  201. {
  202. Name: volumeName,
  203. MountPath: mountPath,
  204. },
  205. }
  206. volumes := []v1.Volume{
  207. {
  208. Name: volumeName,
  209. VolumeSource: v1.VolumeSource{
  210. HostPath: &v1.HostPathVolumeSource{
  211. Path: volumeHostPath,
  212. },
  213. },
  214. },
  215. }
  216. pod.Spec.Containers[0].VolumeMounts = volumeMounts
  217. pod.Spec.Volumes = volumes
  218. pod.Spec.Containers[0].Command = []string{"cat", testFilePath}
  219. pod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{
  220. Level: "s0:c0,c1",
  221. }
  222. f.TestContainerOutput("Pod with same MCS label reading test file", pod, 0, []string{testContent})
  223. // Confirm that the same pod with a different MCS
  224. // label cannot access the volume
  225. ginkgo.By("confirming a container with a different MCS label is unable to read the file")
  226. pod = scTestPod(hostIPC, hostPID)
  227. pod.Spec.Volumes = volumes
  228. pod.Spec.Containers[0].VolumeMounts = volumeMounts
  229. pod.Spec.Containers[0].Command = []string{"sleep", "6000"}
  230. pod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{
  231. Level: "s0:c2,c3",
  232. }
  233. _, err = client.Create(context.TODO(), pod, metav1.CreateOptions{})
  234. framework.ExpectNoError(err, "Error creating pod %v", pod)
  235. err = f.WaitForPodRunning(pod.Name)
  236. framework.ExpectNoError(err, "Error waiting for pod to run %v", pod)
  237. // for this to work, SELinux should be in enforcing mode, so let's check that
  238. isEnforced, err := tk.ReadFileViaContainer(pod.Name, "test-container", "/sys/fs/selinux/enforce")
  239. if err == nil && isEnforced == "1" {
  240. _, err = tk.ReadFileViaContainer(pod.Name, "test-container", testFilePath)
  241. framework.ExpectError(err, "expecting SELinux to not let the container with different MCS label to read the file")
  242. }
  243. }