apparmor_test.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 e2e_node
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "os/exec"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "k8s.io/kubernetes/pkg/api"
  24. "k8s.io/kubernetes/pkg/security/apparmor"
  25. "k8s.io/kubernetes/test/e2e/framework"
  26. "github.com/davecgh/go-spew/spew"
  27. "github.com/golang/glog"
  28. . "github.com/onsi/ginkgo"
  29. . "github.com/onsi/gomega"
  30. )
  31. var _ = framework.KubeDescribe("AppArmor [Feature:AppArmor]", func() {
  32. if isAppArmorEnabled() {
  33. testAppArmorNode()
  34. } else {
  35. testNonAppArmorNode()
  36. }
  37. })
  38. func testAppArmorNode() {
  39. BeforeEach(func() {
  40. By("Loading AppArmor profiles for testing")
  41. framework.ExpectNoError(loadTestProfiles(), "Could not load AppArmor test profiles")
  42. })
  43. Context("when running with AppArmor", func() {
  44. f := framework.NewDefaultFramework("apparmor-test")
  45. It("should reject an unloaded profile", func() {
  46. status := runAppArmorTest(f, apparmor.ProfileNamePrefix+"non-existant-profile")
  47. Expect(status.Phase).To(Equal(api.PodFailed), "PodStatus: %+v", status)
  48. Expect(status.Reason).To(Equal("AppArmor"), "PodStatus: %+v", status)
  49. })
  50. It("should enforce a profile blocking writes", func() {
  51. status := runAppArmorTest(f, apparmor.ProfileNamePrefix+apparmorProfilePrefix+"deny-write")
  52. if len(status.ContainerStatuses) == 0 {
  53. framework.Failf("Unexpected pod status: %s", spew.Sdump(status))
  54. return
  55. }
  56. state := status.ContainerStatuses[0].State.Terminated
  57. Expect(state.ExitCode).To(Not(BeZero()), "ContainerStateTerminated: %+v", state)
  58. })
  59. It("should enforce a permissive profile", func() {
  60. status := runAppArmorTest(f, apparmor.ProfileNamePrefix+apparmorProfilePrefix+"audit-write")
  61. if len(status.ContainerStatuses) == 0 {
  62. framework.Failf("Unexpected pod status: %s", spew.Sdump(status))
  63. return
  64. }
  65. state := status.ContainerStatuses[0].State.Terminated
  66. Expect(state.ExitCode).To(BeZero(), "ContainerStateTerminated: %+v", state)
  67. })
  68. })
  69. }
  70. func testNonAppArmorNode() {
  71. Context("when running without AppArmor", func() {
  72. f := framework.NewDefaultFramework("apparmor-test")
  73. It("should reject a pod with an AppArmor profile", func() {
  74. status := runAppArmorTest(f, apparmor.ProfileRuntimeDefault)
  75. Expect(status.Phase).To(Equal(api.PodFailed), "PodStatus: %+v", status)
  76. Expect(status.Reason).To(Equal("AppArmor"), "PodStatus: %+v", status)
  77. })
  78. })
  79. }
  80. const apparmorProfilePrefix = "e2e-node-apparmor-test-"
  81. const testProfiles = `
  82. #include <tunables/global>
  83. profile e2e-node-apparmor-test-deny-write flags=(attach_disconnected) {
  84. #include <abstractions/base>
  85. file,
  86. # Deny all file writes.
  87. deny /** w,
  88. }
  89. profile e2e-node-apparmor-test-audit-write flags=(attach_disconnected) {
  90. #include <abstractions/base>
  91. file,
  92. # Only audit file writes.
  93. audit /** w,
  94. }
  95. `
  96. func loadTestProfiles() error {
  97. f, err := ioutil.TempFile("/tmp", "apparmor")
  98. if err != nil {
  99. return fmt.Errorf("failed to open temp file: %v", err)
  100. }
  101. defer os.Remove(f.Name())
  102. defer f.Close()
  103. if _, err := f.WriteString(testProfiles); err != nil {
  104. return fmt.Errorf("failed to write profiles to file: %v", err)
  105. }
  106. cmd := exec.Command("sudo", "apparmor_parser", "-r", "-W", f.Name())
  107. stderr := &bytes.Buffer{}
  108. cmd.Stderr = stderr
  109. out, err := cmd.Output()
  110. // apparmor_parser does not always return an error code, so consider any stderr output an error.
  111. if err != nil || stderr.Len() > 0 {
  112. if stderr.Len() > 0 {
  113. glog.Warning(stderr.String())
  114. }
  115. if len(out) > 0 {
  116. glog.Infof("apparmor_parser: %s", out)
  117. }
  118. return fmt.Errorf("failed to load profiles: %v", err)
  119. }
  120. glog.V(2).Infof("Loaded profiles: %v", out)
  121. return nil
  122. }
  123. func runAppArmorTest(f *framework.Framework, profile string) api.PodStatus {
  124. pod := createPodWithAppArmor(f, profile)
  125. // The pod needs to start before it stops, so wait for the longer start timeout.
  126. framework.ExpectNoError(framework.WaitTimeoutForPodNoLongerRunningInNamespace(
  127. f.Client, pod.Name, f.Namespace.Name, "", framework.PodStartTimeout))
  128. p, err := f.PodClient().Get(pod.Name)
  129. framework.ExpectNoError(err)
  130. return p.Status
  131. }
  132. func createPodWithAppArmor(f *framework.Framework, profile string) *api.Pod {
  133. pod := &api.Pod{
  134. ObjectMeta: api.ObjectMeta{
  135. Name: fmt.Sprintf("test-apparmor-%s", strings.Replace(profile, "/", "-", -1)),
  136. Annotations: map[string]string{
  137. apparmor.ContainerAnnotationKeyPrefix + "test": profile,
  138. },
  139. },
  140. Spec: api.PodSpec{
  141. Containers: []api.Container{{
  142. Name: "test",
  143. Image: ImageRegistry[busyBoxImage],
  144. Command: []string{"touch", "foo"},
  145. }},
  146. RestartPolicy: api.RestartPolicyNever,
  147. },
  148. }
  149. return f.PodClient().Create(pod)
  150. }
  151. func isAppArmorEnabled() bool {
  152. // TODO(timstclair): Pass this through the image setup rather than hardcoding.
  153. if strings.Contains(framework.TestContext.NodeName, "-gci-dev-") {
  154. gciVersionRe := regexp.MustCompile("-gci-dev-([0-9]+)-")
  155. matches := gciVersionRe.FindStringSubmatch(framework.TestContext.NodeName)
  156. if len(matches) == 2 {
  157. version, err := strconv.Atoi(matches[1])
  158. if err != nil {
  159. glog.Errorf("Error parsing GCI version from NodeName %q: %v", framework.TestContext.NodeName, err)
  160. return false
  161. }
  162. return version >= 54
  163. }
  164. return false
  165. }
  166. if strings.Contains(framework.TestContext.NodeName, "-ubuntu-") {
  167. return true
  168. }
  169. return apparmor.IsAppArmorEnabled()
  170. }