validate.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 apparmor
  14. import (
  15. "bufio"
  16. "errors"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "strings"
  22. "k8s.io/api/core/v1"
  23. utilfeature "k8s.io/apiserver/pkg/util/feature"
  24. "k8s.io/kubernetes/pkg/features"
  25. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  26. utilpath "k8s.io/utils/path"
  27. )
  28. // Whether AppArmor should be disabled by default.
  29. // Set to true if the wrong build tags are set (see validate_disabled.go).
  30. var isDisabledBuild bool
  31. // Interface for validating that a pod with an AppArmor profile can be run by a Node.
  32. type Validator interface {
  33. Validate(pod *v1.Pod) error
  34. ValidateHost() error
  35. }
  36. func NewValidator(runtime string) Validator {
  37. if err := validateHost(runtime); err != nil {
  38. return &validator{validateHostErr: err}
  39. }
  40. appArmorFS, err := getAppArmorFS()
  41. if err != nil {
  42. return &validator{
  43. validateHostErr: fmt.Errorf("error finding AppArmor FS: %v", err),
  44. }
  45. }
  46. return &validator{
  47. appArmorFS: appArmorFS,
  48. }
  49. }
  50. type validator struct {
  51. validateHostErr error
  52. appArmorFS string
  53. }
  54. func (v *validator) Validate(pod *v1.Pod) error {
  55. if !isRequired(pod) {
  56. return nil
  57. }
  58. if v.ValidateHost() != nil {
  59. return v.validateHostErr
  60. }
  61. loadedProfiles, err := v.getLoadedProfiles()
  62. if err != nil {
  63. return fmt.Errorf("could not read loaded profiles: %v", err)
  64. }
  65. for _, container := range pod.Spec.InitContainers {
  66. if err := validateProfile(GetProfileName(pod, container.Name), loadedProfiles); err != nil {
  67. return err
  68. }
  69. }
  70. for _, container := range pod.Spec.Containers {
  71. if err := validateProfile(GetProfileName(pod, container.Name), loadedProfiles); err != nil {
  72. return err
  73. }
  74. }
  75. return nil
  76. }
  77. func (v *validator) ValidateHost() error {
  78. return v.validateHostErr
  79. }
  80. // Verify that the host and runtime is capable of enforcing AppArmor profiles.
  81. func validateHost(runtime string) error {
  82. // Check feature-gates
  83. if !utilfeature.DefaultFeatureGate.Enabled(features.AppArmor) {
  84. return errors.New("AppArmor disabled by feature-gate")
  85. }
  86. // Check build support.
  87. if isDisabledBuild {
  88. return errors.New("Binary not compiled for linux")
  89. }
  90. // Check kernel support.
  91. if !IsAppArmorEnabled() {
  92. return errors.New("AppArmor is not enabled on the host")
  93. }
  94. // Check runtime support. Currently only Docker is supported.
  95. if runtime != kubetypes.DockerContainerRuntime && runtime != kubetypes.RemoteContainerRuntime {
  96. return fmt.Errorf("AppArmor is only enabled for 'docker' and 'remote' runtimes. Found: %q.", runtime)
  97. }
  98. return nil
  99. }
  100. // Verify that the profile is valid and loaded.
  101. func validateProfile(profile string, loadedProfiles map[string]bool) error {
  102. if err := ValidateProfileFormat(profile); err != nil {
  103. return err
  104. }
  105. if strings.HasPrefix(profile, ProfileNamePrefix) {
  106. profileName := strings.TrimPrefix(profile, ProfileNamePrefix)
  107. if !loadedProfiles[profileName] {
  108. return fmt.Errorf("profile %q is not loaded", profileName)
  109. }
  110. }
  111. return nil
  112. }
  113. func ValidateProfileFormat(profile string) error {
  114. if profile == "" || profile == ProfileRuntimeDefault || profile == ProfileNameUnconfined {
  115. return nil
  116. }
  117. if !strings.HasPrefix(profile, ProfileNamePrefix) {
  118. return fmt.Errorf("invalid AppArmor profile name: %q", profile)
  119. }
  120. return nil
  121. }
  122. func (v *validator) getLoadedProfiles() (map[string]bool, error) {
  123. profilesPath := path.Join(v.appArmorFS, "profiles")
  124. profilesFile, err := os.Open(profilesPath)
  125. if err != nil {
  126. return nil, fmt.Errorf("failed to open %s: %v", profilesPath, err)
  127. }
  128. defer profilesFile.Close()
  129. profiles := map[string]bool{}
  130. scanner := bufio.NewScanner(profilesFile)
  131. for scanner.Scan() {
  132. profileName := parseProfileName(scanner.Text())
  133. if profileName == "" {
  134. // Unknown line format; skip it.
  135. continue
  136. }
  137. profiles[profileName] = true
  138. }
  139. return profiles, nil
  140. }
  141. // The profiles file is formatted with one profile per line, matching a form:
  142. // namespace://profile-name (mode)
  143. // profile-name (mode)
  144. // Where mode is {enforce, complain, kill}. The "namespace://" is only included for namespaced
  145. // profiles. For the purposes of Kubernetes, we consider the namespace part of the profile name.
  146. func parseProfileName(profileLine string) string {
  147. modeIndex := strings.IndexRune(profileLine, '(')
  148. if modeIndex < 0 {
  149. return ""
  150. }
  151. return strings.TrimSpace(profileLine[:modeIndex])
  152. }
  153. func getAppArmorFS() (string, error) {
  154. mountsFile, err := os.Open("/proc/mounts")
  155. if err != nil {
  156. return "", fmt.Errorf("could not open /proc/mounts: %v", err)
  157. }
  158. defer mountsFile.Close()
  159. scanner := bufio.NewScanner(mountsFile)
  160. for scanner.Scan() {
  161. fields := strings.Fields(scanner.Text())
  162. if len(fields) < 3 {
  163. // Unknown line format; skip it.
  164. continue
  165. }
  166. if fields[2] == "securityfs" {
  167. appArmorFS := path.Join(fields[1], "apparmor")
  168. if ok, err := utilpath.Exists(utilpath.CheckFollowSymlink, appArmorFS); !ok {
  169. msg := fmt.Sprintf("path %s does not exist", appArmorFS)
  170. if err != nil {
  171. return "", fmt.Errorf("%s: %v", msg, err)
  172. } else {
  173. return "", errors.New(msg)
  174. }
  175. } else {
  176. return appArmorFS, nil
  177. }
  178. }
  179. }
  180. if err := scanner.Err(); err != nil {
  181. return "", fmt.Errorf("error scanning mounts: %v", err)
  182. }
  183. return "", errors.New("securityfs not found")
  184. }
  185. // IsAppArmorEnabled returns true if apparmor is enabled for the host.
  186. // This function is forked from
  187. // https://github.com/opencontainers/runc/blob/1a81e9ab1f138c091fe5c86d0883f87716088527/libcontainer/apparmor/apparmor.go
  188. // to avoid the libapparmor dependency.
  189. func IsAppArmorEnabled() bool {
  190. if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil && os.Getenv("container") == "" {
  191. if _, err = os.Stat("/sbin/apparmor_parser"); err == nil {
  192. buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
  193. return err == nil && len(buf) > 1 && buf[0] == 'Y'
  194. }
  195. }
  196. return false
  197. }