validate.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  25. "k8s.io/kubernetes/pkg/features"
  26. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  27. utilpath "k8s.io/utils/path"
  28. )
  29. // Whether AppArmor should be disabled by default.
  30. // Set to true if the wrong build tags are set (see validate_disabled.go).
  31. var isDisabledBuild bool
  32. // Validator is a interface for validating that a pod with an AppArmor profile can be run by a Node.
  33. type Validator interface {
  34. Validate(pod *v1.Pod) error
  35. ValidateHost() error
  36. }
  37. // NewValidator is in order to find AppArmor FS
  38. func NewValidator(runtime string) Validator {
  39. if err := validateHost(runtime); err != nil {
  40. return &validator{validateHostErr: err}
  41. }
  42. appArmorFS, err := getAppArmorFS()
  43. if err != nil {
  44. return &validator{
  45. validateHostErr: fmt.Errorf("error finding AppArmor FS: %v", err),
  46. }
  47. }
  48. return &validator{
  49. appArmorFS: appArmorFS,
  50. }
  51. }
  52. type validator struct {
  53. validateHostErr error
  54. appArmorFS string
  55. }
  56. func (v *validator) Validate(pod *v1.Pod) error {
  57. if !isRequired(pod) {
  58. return nil
  59. }
  60. if v.ValidateHost() != nil {
  61. return v.validateHostErr
  62. }
  63. loadedProfiles, err := v.getLoadedProfiles()
  64. if err != nil {
  65. return fmt.Errorf("could not read loaded profiles: %v", err)
  66. }
  67. var retErr error
  68. podutil.VisitContainers(&pod.Spec, func(container *v1.Container) bool {
  69. retErr = validateProfile(GetProfileName(pod, container.Name), loadedProfiles)
  70. if retErr != nil {
  71. return false
  72. }
  73. return true
  74. })
  75. return retErr
  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. // ValidateProfileFormat checks the format of the profile.
  114. func ValidateProfileFormat(profile string) error {
  115. if profile == "" || profile == ProfileRuntimeDefault || profile == ProfileNameUnconfined {
  116. return nil
  117. }
  118. if !strings.HasPrefix(profile, ProfileNamePrefix) {
  119. return fmt.Errorf("invalid AppArmor profile name: %q", profile)
  120. }
  121. return nil
  122. }
  123. func (v *validator) getLoadedProfiles() (map[string]bool, error) {
  124. profilesPath := path.Join(v.appArmorFS, "profiles")
  125. profilesFile, err := os.Open(profilesPath)
  126. if err != nil {
  127. return nil, fmt.Errorf("failed to open %s: %v", profilesPath, err)
  128. }
  129. defer profilesFile.Close()
  130. profiles := map[string]bool{}
  131. scanner := bufio.NewScanner(profilesFile)
  132. for scanner.Scan() {
  133. profileName := parseProfileName(scanner.Text())
  134. if profileName == "" {
  135. // Unknown line format; skip it.
  136. continue
  137. }
  138. profiles[profileName] = true
  139. }
  140. return profiles, nil
  141. }
  142. // The profiles file is formatted with one profile per line, matching a form:
  143. // namespace://profile-name (mode)
  144. // profile-name (mode)
  145. // Where mode is {enforce, complain, kill}. The "namespace://" is only included for namespaced
  146. // profiles. For the purposes of Kubernetes, we consider the namespace part of the profile name.
  147. func parseProfileName(profileLine string) string {
  148. modeIndex := strings.IndexRune(profileLine, '(')
  149. if modeIndex < 0 {
  150. return ""
  151. }
  152. return strings.TrimSpace(profileLine[:modeIndex])
  153. }
  154. func getAppArmorFS() (string, error) {
  155. mountsFile, err := os.Open("/proc/mounts")
  156. if err != nil {
  157. return "", fmt.Errorf("could not open /proc/mounts: %v", err)
  158. }
  159. defer mountsFile.Close()
  160. scanner := bufio.NewScanner(mountsFile)
  161. for scanner.Scan() {
  162. fields := strings.Fields(scanner.Text())
  163. if len(fields) < 3 {
  164. // Unknown line format; skip it.
  165. continue
  166. }
  167. if fields[2] == "securityfs" {
  168. appArmorFS := path.Join(fields[1], "apparmor")
  169. if ok, err := utilpath.Exists(utilpath.CheckFollowSymlink, appArmorFS); !ok {
  170. msg := fmt.Sprintf("path %s does not exist", appArmorFS)
  171. if err != nil {
  172. return "", fmt.Errorf("%s: %v", msg, err)
  173. }
  174. return "", errors.New(msg)
  175. }
  176. return appArmorFS, nil
  177. }
  178. }
  179. if err := scanner.Err(); err != nil {
  180. return "", fmt.Errorf("error scanning mounts: %v", err)
  181. }
  182. return "", errors.New("securityfs not found")
  183. }
  184. // IsAppArmorEnabled returns true if apparmor is enabled for the host.
  185. // This function is forked from
  186. // https://github.com/opencontainers/runc/blob/1a81e9ab1f138c091fe5c86d0883f87716088527/libcontainer/apparmor/apparmor.go
  187. // to avoid the libapparmor dependency.
  188. func IsAppArmorEnabled() bool {
  189. if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil && os.Getenv("container") == "" {
  190. if _, err = os.Stat("/sbin/apparmor_parser"); err == nil {
  191. buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
  192. return err == nil && len(buf) > 1 && buf[0] == 'Y'
  193. }
  194. }
  195. return false
  196. }