validate.go 6.0 KB

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