security_context.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 common
  14. import (
  15. "fmt"
  16. "strings"
  17. "time"
  18. v1 "k8s.io/api/core/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/util/uuid"
  21. "k8s.io/kubernetes/pkg/kubelet/events"
  22. "k8s.io/kubernetes/test/e2e/framework"
  23. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  24. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  25. imageutils "k8s.io/kubernetes/test/utils/image"
  26. "k8s.io/utils/pointer"
  27. "github.com/onsi/ginkgo"
  28. "github.com/onsi/gomega"
  29. )
  30. var _ = framework.KubeDescribe("Security Context", func() {
  31. f := framework.NewDefaultFramework("security-context-test")
  32. var podClient *framework.PodClient
  33. ginkgo.BeforeEach(func() {
  34. podClient = f.PodClient()
  35. })
  36. ginkgo.Context("When creating a container with runAsUser", func() {
  37. makeUserPod := func(podName, image string, command []string, userid int64) *v1.Pod {
  38. return &v1.Pod{
  39. ObjectMeta: metav1.ObjectMeta{
  40. Name: podName,
  41. },
  42. Spec: v1.PodSpec{
  43. RestartPolicy: v1.RestartPolicyNever,
  44. Containers: []v1.Container{
  45. {
  46. Image: image,
  47. Name: podName,
  48. Command: command,
  49. SecurityContext: &v1.SecurityContext{
  50. RunAsUser: &userid,
  51. },
  52. },
  53. },
  54. },
  55. }
  56. }
  57. createAndWaitUserPod := func(userid int64) {
  58. podName := fmt.Sprintf("busybox-user-%d-%s", userid, uuid.NewUUID())
  59. podClient.Create(makeUserPod(podName,
  60. framework.BusyBoxImage,
  61. []string{"sh", "-c", fmt.Sprintf("test $(id -u) -eq %d", userid)},
  62. userid,
  63. ))
  64. podClient.WaitForSuccess(podName, framework.PodStartTimeout)
  65. }
  66. /*
  67. Release : v1.15
  68. Testname: Security Context, runAsUser=65534
  69. Description: Container is created with runAsUser option by passing uid 65534 to run as unpriviledged user. Pod MUST be in Succeeded phase.
  70. [LinuxOnly]: This test is marked as LinuxOnly since Windows does not support running as UID / GID.
  71. */
  72. framework.ConformanceIt("should run the container with uid 65534 [LinuxOnly] [NodeConformance]", func() {
  73. createAndWaitUserPod(65534)
  74. })
  75. /*
  76. Release : v1.15
  77. Testname: Security Context, runAsUser=0
  78. Description: Container is created with runAsUser option by passing uid 0 to run as root priviledged user. Pod MUST be in Succeeded phase.
  79. This e2e can not be promoted to Conformance because a Conformant platform may not allow to run containers with 'uid 0' or running privileged operations.
  80. [LinuxOnly]: This test is marked as LinuxOnly since Windows does not support running as UID / GID.
  81. */
  82. ginkgo.It("should run the container with uid 0 [LinuxOnly] [NodeConformance]", func() {
  83. createAndWaitUserPod(0)
  84. })
  85. })
  86. ginkgo.Context("When creating a container with runAsNonRoot", func() {
  87. rootImage := imageutils.GetE2EImage(imageutils.BusyBox)
  88. nonRootImage := imageutils.GetE2EImage(imageutils.NonRoot)
  89. makeNonRootPod := func(podName, image string, userid *int64) *v1.Pod {
  90. return &v1.Pod{
  91. ObjectMeta: metav1.ObjectMeta{
  92. Name: podName,
  93. },
  94. Spec: v1.PodSpec{
  95. RestartPolicy: v1.RestartPolicyNever,
  96. Containers: []v1.Container{
  97. {
  98. Image: image,
  99. Name: podName,
  100. Command: []string{"id", "-u"}, // Print UID and exit
  101. SecurityContext: &v1.SecurityContext{
  102. RunAsNonRoot: pointer.BoolPtr(true),
  103. RunAsUser: userid,
  104. },
  105. },
  106. },
  107. },
  108. }
  109. }
  110. ginkgo.It("should run with an explicit non-root user ID [LinuxOnly]", func() {
  111. // creates a pod with RunAsUser, which is not supported on Windows.
  112. e2eskipper.SkipIfNodeOSDistroIs("windows")
  113. name := "explicit-nonroot-uid"
  114. pod := makeNonRootPod(name, rootImage, pointer.Int64Ptr(nonRootTestUserID))
  115. podClient.Create(pod)
  116. podClient.WaitForSuccess(name, framework.PodStartTimeout)
  117. framework.ExpectNoError(podClient.MatchContainerOutput(name, name, "1000"))
  118. })
  119. ginkgo.It("should not run with an explicit root user ID [LinuxOnly]", func() {
  120. // creates a pod with RunAsUser, which is not supported on Windows.
  121. e2eskipper.SkipIfNodeOSDistroIs("windows")
  122. name := "explicit-root-uid"
  123. pod := makeNonRootPod(name, nonRootImage, pointer.Int64Ptr(0))
  124. pod = podClient.Create(pod)
  125. ev, err := podClient.WaitForErrorEventOrSuccess(pod)
  126. framework.ExpectNoError(err)
  127. gomega.Expect(ev).NotTo(gomega.BeNil())
  128. framework.ExpectEqual(ev.Reason, events.FailedToCreateContainer)
  129. })
  130. ginkgo.It("should run with an image specified user ID", func() {
  131. name := "implicit-nonroot-uid"
  132. pod := makeNonRootPod(name, nonRootImage, nil)
  133. podClient.Create(pod)
  134. podClient.WaitForSuccess(name, framework.PodStartTimeout)
  135. framework.ExpectNoError(podClient.MatchContainerOutput(name, name, "1234"))
  136. })
  137. ginkgo.It("should not run without a specified user ID", func() {
  138. name := "implicit-root-uid"
  139. pod := makeNonRootPod(name, rootImage, nil)
  140. pod = podClient.Create(pod)
  141. ev, err := podClient.WaitForErrorEventOrSuccess(pod)
  142. framework.ExpectNoError(err)
  143. gomega.Expect(ev).NotTo(gomega.BeNil())
  144. framework.ExpectEqual(ev.Reason, events.FailedToCreateContainer)
  145. })
  146. })
  147. ginkgo.Context("When creating a pod with readOnlyRootFilesystem", func() {
  148. makeUserPod := func(podName, image string, command []string, readOnlyRootFilesystem bool) *v1.Pod {
  149. return &v1.Pod{
  150. ObjectMeta: metav1.ObjectMeta{
  151. Name: podName,
  152. },
  153. Spec: v1.PodSpec{
  154. RestartPolicy: v1.RestartPolicyNever,
  155. Containers: []v1.Container{
  156. {
  157. Image: image,
  158. Name: podName,
  159. Command: command,
  160. SecurityContext: &v1.SecurityContext{
  161. ReadOnlyRootFilesystem: &readOnlyRootFilesystem,
  162. },
  163. },
  164. },
  165. },
  166. }
  167. }
  168. createAndWaitUserPod := func(readOnlyRootFilesystem bool) string {
  169. podName := fmt.Sprintf("busybox-readonly-%v-%s", readOnlyRootFilesystem, uuid.NewUUID())
  170. podClient.Create(makeUserPod(podName,
  171. framework.BusyBoxImage,
  172. []string{"sh", "-c", "touch checkfile"},
  173. readOnlyRootFilesystem,
  174. ))
  175. if readOnlyRootFilesystem {
  176. waitForFailure(f, podName, framework.PodStartTimeout)
  177. } else {
  178. podClient.WaitForSuccess(podName, framework.PodStartTimeout)
  179. }
  180. return podName
  181. }
  182. /*
  183. Release : v1.15
  184. Testname: Security Context, readOnlyRootFilesystem=true.
  185. Description: Container is configured to run with readOnlyRootFilesystem to true which will force containers to run with a read only root file system.
  186. Write operation MUST NOT be allowed and Pod MUST be in Failed state.
  187. At this moment we are not considering this test for Conformance due to use of SecurityContext.
  188. [LinuxOnly]: This test is marked as LinuxOnly since Windows does not support creating containers with read-only access.
  189. */
  190. ginkgo.It("should run the container with readonly rootfs when readOnlyRootFilesystem=true [LinuxOnly] [NodeConformance]", func() {
  191. createAndWaitUserPod(true)
  192. })
  193. /*
  194. Release : v1.15
  195. Testname: Security Context, readOnlyRootFilesystem=false.
  196. Description: Container is configured to run with readOnlyRootFilesystem to false.
  197. Write operation MUST be allowed and Pod MUST be in Succeeded state.
  198. */
  199. framework.ConformanceIt("should run the container with writable rootfs when readOnlyRootFilesystem=false [NodeConformance]", func() {
  200. createAndWaitUserPod(false)
  201. })
  202. })
  203. ginkgo.Context("When creating a pod with privileged", func() {
  204. makeUserPod := func(podName, image string, command []string, privileged bool) *v1.Pod {
  205. return &v1.Pod{
  206. ObjectMeta: metav1.ObjectMeta{
  207. Name: podName,
  208. },
  209. Spec: v1.PodSpec{
  210. RestartPolicy: v1.RestartPolicyNever,
  211. Containers: []v1.Container{
  212. {
  213. Image: image,
  214. Name: podName,
  215. Command: command,
  216. SecurityContext: &v1.SecurityContext{
  217. Privileged: &privileged,
  218. },
  219. },
  220. },
  221. },
  222. }
  223. }
  224. createAndWaitUserPod := func(privileged bool) string {
  225. podName := fmt.Sprintf("busybox-privileged-%v-%s", privileged, uuid.NewUUID())
  226. podClient.Create(makeUserPod(podName,
  227. framework.BusyBoxImage,
  228. []string{"sh", "-c", "ip link add dummy0 type dummy || true"},
  229. privileged,
  230. ))
  231. podClient.WaitForSuccess(podName, framework.PodStartTimeout)
  232. return podName
  233. }
  234. /*
  235. Release : v1.15
  236. Testname: Security Context, privileged=false.
  237. Description: Create a container to run in unprivileged mode by setting pod's SecurityContext Privileged option as false. Pod MUST be in Succeeded phase.
  238. [LinuxOnly]: This test is marked as LinuxOnly since it runs a Linux-specific command.
  239. */
  240. framework.ConformanceIt("should run the container as unprivileged when false [LinuxOnly] [NodeConformance]", func() {
  241. podName := createAndWaitUserPod(false)
  242. logs, err := e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, podName, podName)
  243. if err != nil {
  244. framework.Failf("GetPodLogs for pod %q failed: %v", podName, err)
  245. }
  246. framework.Logf("Got logs for pod %q: %q", podName, logs)
  247. if !strings.Contains(logs, "Operation not permitted") {
  248. framework.Failf("unprivileged container shouldn't be able to create dummy device")
  249. }
  250. })
  251. ginkgo.It("should run the container as privileged when true [LinuxOnly] [NodeFeature:HostAccess]", func() {
  252. podName := createAndWaitUserPod(true)
  253. logs, err := e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, podName, podName)
  254. if err != nil {
  255. framework.Failf("GetPodLogs for pod %q failed: %v", podName, err)
  256. }
  257. framework.Logf("Got logs for pod %q: %q", podName, logs)
  258. if strings.Contains(logs, "Operation not permitted") {
  259. framework.Failf("privileged container should be able to create dummy device")
  260. }
  261. })
  262. })
  263. ginkgo.Context("when creating containers with AllowPrivilegeEscalation", func() {
  264. makeAllowPrivilegeEscalationPod := func(podName string, allowPrivilegeEscalation *bool, uid int64) *v1.Pod {
  265. return &v1.Pod{
  266. ObjectMeta: metav1.ObjectMeta{
  267. Name: podName,
  268. },
  269. Spec: v1.PodSpec{
  270. RestartPolicy: v1.RestartPolicyNever,
  271. Containers: []v1.Container{
  272. {
  273. Image: imageutils.GetE2EImage(imageutils.Nonewprivs),
  274. Name: podName,
  275. SecurityContext: &v1.SecurityContext{
  276. AllowPrivilegeEscalation: allowPrivilegeEscalation,
  277. RunAsUser: &uid,
  278. },
  279. },
  280. },
  281. },
  282. }
  283. }
  284. createAndMatchOutput := func(podName, output string, allowPrivilegeEscalation *bool, uid int64) error {
  285. podClient.Create(makeAllowPrivilegeEscalationPod(podName,
  286. allowPrivilegeEscalation,
  287. uid,
  288. ))
  289. podClient.WaitForSuccess(podName, framework.PodStartTimeout)
  290. return podClient.MatchContainerOutput(podName, podName, output)
  291. }
  292. /*
  293. Release : v1.15
  294. Testname: Security Context, allowPrivilegeEscalation unset, uid != 0.
  295. Description: Configuring the allowPrivilegeEscalation unset, allows the privilege escalation operation.
  296. A container is configured with allowPrivilegeEscalation not specified (nil) and a given uid which is not 0.
  297. When the container is run, container's output MUST match with expected output verifying container ran with uid=0.
  298. This e2e Can not be promoted to Conformance as it is Container Runtime dependent and not all conformant platforms will require this behavior.
  299. [LinuxOnly]: This test is marked LinuxOnly since Windows does not support running as UID / GID, or privilege escalation.
  300. */
  301. ginkgo.It("should allow privilege escalation when not explicitly set and uid != 0 [LinuxOnly] [NodeConformance]", func() {
  302. podName := "alpine-nnp-nil-" + string(uuid.NewUUID())
  303. if err := createAndMatchOutput(podName, "Effective uid: 0", nil, nonRootTestUserID); err != nil {
  304. framework.Failf("Match output for pod %q failed: %v", podName, err)
  305. }
  306. })
  307. /*
  308. Release : v1.15
  309. Testname: Security Context, allowPrivilegeEscalation=false.
  310. Description: Configuring the allowPrivilegeEscalation to false, does not allow the privilege escalation operation.
  311. A container is configured with allowPrivilegeEscalation=false and a given uid (1000) which is not 0.
  312. When the container is run, container's output MUST match with expected output verifying container ran with given uid i.e. uid=1000.
  313. [LinuxOnly]: This test is marked LinuxOnly since Windows does not support running as UID / GID, or privilege escalation.
  314. */
  315. framework.ConformanceIt("should not allow privilege escalation when false [LinuxOnly] [NodeConformance]", func() {
  316. podName := "alpine-nnp-false-" + string(uuid.NewUUID())
  317. apeFalse := false
  318. if err := createAndMatchOutput(podName, fmt.Sprintf("Effective uid: %d", nonRootTestUserID), &apeFalse, nonRootTestUserID); err != nil {
  319. framework.Failf("Match output for pod %q failed: %v", podName, err)
  320. }
  321. })
  322. /*
  323. Release : v1.15
  324. Testname: Security Context, allowPrivilegeEscalation=true.
  325. Description: Configuring the allowPrivilegeEscalation to true, allows the privilege escalation operation.
  326. A container is configured with allowPrivilegeEscalation=true and a given uid (1000) which is not 0.
  327. When the container is run, container's output MUST match with expected output verifying container ran with uid=0 (making use of the privilege escalation).
  328. This e2e Can not be promoted to Conformance as it is Container Runtime dependent and runtime may not allow to run.
  329. [LinuxOnly]: This test is marked LinuxOnly since Windows does not support running as UID / GID.
  330. */
  331. ginkgo.It("should allow privilege escalation when true [LinuxOnly] [NodeConformance]", func() {
  332. podName := "alpine-nnp-true-" + string(uuid.NewUUID())
  333. apeTrue := true
  334. if err := createAndMatchOutput(podName, "Effective uid: 0", &apeTrue, nonRootTestUserID); err != nil {
  335. framework.Failf("Match output for pod %q failed: %v", podName, err)
  336. }
  337. })
  338. })
  339. })
  340. // waitForFailure waits for pod to fail.
  341. func waitForFailure(f *framework.Framework, name string, timeout time.Duration) {
  342. gomega.Expect(e2epod.WaitForPodCondition(f.ClientSet, f.Namespace.Name, name, fmt.Sprintf("%s or %s", v1.PodSucceeded, v1.PodFailed), timeout,
  343. func(pod *v1.Pod) (bool, error) {
  344. switch pod.Status.Phase {
  345. case v1.PodFailed:
  346. return true, nil
  347. case v1.PodSucceeded:
  348. return true, fmt.Errorf("pod %q successed with reason: %q, message: %q", name, pod.Status.Reason, pod.Status.Message)
  349. default:
  350. return false, nil
  351. }
  352. },
  353. )).To(gomega.Succeed(), "wait for pod %q to fail", name)
  354. }