apparmor.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 security
  14. import (
  15. "context"
  16. "fmt"
  17. v1 "k8s.io/api/core/v1"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/apimachinery/pkg/labels"
  20. clientset "k8s.io/client-go/kubernetes"
  21. "k8s.io/kubernetes/pkg/security/apparmor"
  22. "k8s.io/kubernetes/test/e2e/framework"
  23. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  24. imageutils "k8s.io/kubernetes/test/utils/image"
  25. )
  26. const (
  27. appArmorProfilePrefix = "e2e-apparmor-test-"
  28. appArmorAllowedPath = "/expect_allowed_write"
  29. appArmorDeniedPath = "/expect_permission_denied"
  30. loaderLabelKey = "name"
  31. loaderLabelValue = "e2e-apparmor-loader"
  32. )
  33. // LoadAppArmorProfiles creates apparmor-profiles ConfigMap and apparmor-loader ReplicationController.
  34. func LoadAppArmorProfiles(nsName string, clientset clientset.Interface) {
  35. createAppArmorProfileCM(nsName, clientset)
  36. createAppArmorProfileLoader(nsName, clientset)
  37. }
  38. // CreateAppArmorTestPod creates a pod that tests apparmor profile enforcement. The pod exits with
  39. // an error code if the profile is incorrectly enforced. If runOnce is true the pod will exit after
  40. // a single test, otherwise it will repeat the test every 1 second until failure.
  41. func CreateAppArmorTestPod(nsName string, clientset clientset.Interface, podClient *framework.PodClient, unconfined bool, runOnce bool) *v1.Pod {
  42. profile := "localhost/" + appArmorProfilePrefix + nsName
  43. testCmd := fmt.Sprintf(`
  44. if touch %[1]s; then
  45. echo "FAILURE: write to %[1]s should be denied"
  46. exit 1
  47. elif ! touch %[2]s; then
  48. echo "FAILURE: write to %[2]s should be allowed"
  49. exit 2
  50. elif [[ $(< /proc/self/attr/current) != "%[3]s" ]]; then
  51. echo "FAILURE: not running with expected profile %[3]s"
  52. echo "found: $(cat /proc/self/attr/current)"
  53. exit 3
  54. fi`, appArmorDeniedPath, appArmorAllowedPath, appArmorProfilePrefix+nsName)
  55. if unconfined {
  56. profile = apparmor.ProfileNameUnconfined
  57. testCmd = `
  58. if cat /proc/sysrq-trigger 2>&1 | grep 'Permission denied'; then
  59. echo 'FAILURE: reading /proc/sysrq-trigger should be allowed'
  60. exit 1
  61. elif [[ $(< /proc/self/attr/current) != "unconfined" ]]; then
  62. echo 'FAILURE: not running with expected profile unconfined'
  63. exit 2
  64. fi`
  65. }
  66. if !runOnce {
  67. testCmd = fmt.Sprintf(`while true; do
  68. %s
  69. sleep 1
  70. done`, testCmd)
  71. }
  72. loaderAffinity := &v1.Affinity{
  73. PodAffinity: &v1.PodAffinity{
  74. RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{{
  75. Namespaces: []string{nsName},
  76. LabelSelector: &metav1.LabelSelector{
  77. MatchLabels: map[string]string{loaderLabelKey: loaderLabelValue},
  78. },
  79. TopologyKey: "kubernetes.io/hostname",
  80. }},
  81. },
  82. }
  83. pod := &v1.Pod{
  84. ObjectMeta: metav1.ObjectMeta{
  85. GenerateName: "test-apparmor-",
  86. Annotations: map[string]string{
  87. apparmor.ContainerAnnotationKeyPrefix + "test": profile,
  88. },
  89. Labels: map[string]string{
  90. "test": "apparmor",
  91. },
  92. },
  93. Spec: v1.PodSpec{
  94. Affinity: loaderAffinity,
  95. Containers: []v1.Container{{
  96. Name: "test",
  97. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  98. Command: []string{"sh", "-c", testCmd},
  99. }},
  100. RestartPolicy: v1.RestartPolicyNever,
  101. },
  102. }
  103. if runOnce {
  104. pod = podClient.Create(pod)
  105. framework.ExpectNoError(e2epod.WaitForPodSuccessInNamespace(
  106. clientset, pod.Name, nsName))
  107. var err error
  108. pod, err = podClient.Get(context.TODO(), pod.Name, metav1.GetOptions{})
  109. framework.ExpectNoError(err)
  110. } else {
  111. pod = podClient.CreateSync(pod)
  112. framework.ExpectNoError(e2epod.WaitTimeoutForPodReadyInNamespace(clientset, pod.Name, nsName, framework.PodStartTimeout))
  113. }
  114. // Verify Pod affinity colocated the Pods.
  115. loader := getRunningLoaderPod(nsName, clientset)
  116. framework.ExpectEqual(pod.Spec.NodeName, loader.Spec.NodeName)
  117. return pod
  118. }
  119. func createAppArmorProfileCM(nsName string, clientset clientset.Interface) {
  120. profileName := appArmorProfilePrefix + nsName
  121. profile := fmt.Sprintf(`#include <tunables/global>
  122. profile %s flags=(attach_disconnected) {
  123. #include <abstractions/base>
  124. file,
  125. deny %s w,
  126. audit %s w,
  127. }
  128. `, profileName, appArmorDeniedPath, appArmorAllowedPath)
  129. cm := &v1.ConfigMap{
  130. ObjectMeta: metav1.ObjectMeta{
  131. Name: "apparmor-profiles",
  132. Namespace: nsName,
  133. },
  134. Data: map[string]string{
  135. profileName: profile,
  136. },
  137. }
  138. _, err := clientset.CoreV1().ConfigMaps(nsName).Create(context.TODO(), cm, metav1.CreateOptions{})
  139. framework.ExpectNoError(err, "Failed to create apparmor-profiles ConfigMap")
  140. }
  141. func createAppArmorProfileLoader(nsName string, clientset clientset.Interface) {
  142. True := true
  143. One := int32(1)
  144. loader := &v1.ReplicationController{
  145. ObjectMeta: metav1.ObjectMeta{
  146. Name: "apparmor-loader",
  147. Namespace: nsName,
  148. },
  149. Spec: v1.ReplicationControllerSpec{
  150. Replicas: &One,
  151. Template: &v1.PodTemplateSpec{
  152. ObjectMeta: metav1.ObjectMeta{
  153. Labels: map[string]string{loaderLabelKey: loaderLabelValue},
  154. },
  155. Spec: v1.PodSpec{
  156. Containers: []v1.Container{{
  157. Name: "apparmor-loader",
  158. Image: imageutils.GetE2EImage(imageutils.AppArmorLoader),
  159. Args: []string{"-poll", "10s", "/profiles"},
  160. SecurityContext: &v1.SecurityContext{
  161. Privileged: &True,
  162. },
  163. VolumeMounts: []v1.VolumeMount{{
  164. Name: "sys",
  165. MountPath: "/sys",
  166. ReadOnly: true,
  167. }, {
  168. Name: "apparmor-includes",
  169. MountPath: "/etc/apparmor.d",
  170. ReadOnly: true,
  171. }, {
  172. Name: "profiles",
  173. MountPath: "/profiles",
  174. ReadOnly: true,
  175. }},
  176. }},
  177. Volumes: []v1.Volume{{
  178. Name: "sys",
  179. VolumeSource: v1.VolumeSource{
  180. HostPath: &v1.HostPathVolumeSource{
  181. Path: "/sys",
  182. },
  183. },
  184. }, {
  185. Name: "apparmor-includes",
  186. VolumeSource: v1.VolumeSource{
  187. HostPath: &v1.HostPathVolumeSource{
  188. Path: "/etc/apparmor.d",
  189. },
  190. },
  191. }, {
  192. Name: "profiles",
  193. VolumeSource: v1.VolumeSource{
  194. ConfigMap: &v1.ConfigMapVolumeSource{
  195. LocalObjectReference: v1.LocalObjectReference{
  196. Name: "apparmor-profiles",
  197. },
  198. },
  199. },
  200. }},
  201. },
  202. },
  203. },
  204. }
  205. _, err := clientset.CoreV1().ReplicationControllers(nsName).Create(context.TODO(), loader, metav1.CreateOptions{})
  206. framework.ExpectNoError(err, "Failed to create apparmor-loader ReplicationController")
  207. // Wait for loader to be ready.
  208. getRunningLoaderPod(nsName, clientset)
  209. }
  210. func getRunningLoaderPod(nsName string, clientset clientset.Interface) *v1.Pod {
  211. label := labels.SelectorFromSet(labels.Set(map[string]string{loaderLabelKey: loaderLabelValue}))
  212. pods, err := e2epod.WaitForPodsWithLabelScheduled(clientset, nsName, label)
  213. framework.ExpectNoError(err, "Failed to schedule apparmor-loader Pod")
  214. pod := &pods.Items[0]
  215. framework.ExpectNoError(e2epod.WaitForPodRunningInNamespace(clientset, pod), "Failed to run apparmor-loader Pod")
  216. return pod
  217. }