loader.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. Copyright 2015 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 main
  14. import (
  15. "bufio"
  16. "bytes"
  17. "flag"
  18. "fmt"
  19. "io/ioutil"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "path/filepath"
  24. "strings"
  25. "time"
  26. "k8s.io/klog"
  27. )
  28. var (
  29. // The directories to load profiles from.
  30. dirs []string
  31. poll = flag.Duration("poll", -1, "Poll the directories for new profiles with this interval. Values < 0 disable polling, and exit after loading the profiles.")
  32. )
  33. const (
  34. parser = "apparmor_parser"
  35. apparmorfs = "/sys/kernel/security/apparmor"
  36. )
  37. func main() {
  38. flag.Usage = func() {
  39. fmt.Fprintf(os.Stderr, "Usage: %s [FLAG]... [PROFILE_DIR]...\n", os.Args[0])
  40. fmt.Fprintf(os.Stderr, "Load the AppArmor profiles specified in the PROFILE_DIR directories.\n")
  41. flag.PrintDefaults()
  42. }
  43. flag.Parse()
  44. dirs = flag.Args()
  45. if len(dirs) == 0 {
  46. klog.Errorf("Must specify at least one directory.")
  47. flag.Usage()
  48. os.Exit(1)
  49. }
  50. // Check that the required parser binary is found.
  51. if _, err := exec.LookPath(parser); err != nil {
  52. klog.Exitf("Required binary %s not found in PATH", parser)
  53. }
  54. // Check that loaded profiles can be read.
  55. if _, err := getLoadedProfiles(); err != nil {
  56. klog.Exitf("Unable to access apparmor profiles: %v", err)
  57. }
  58. if *poll < 0 {
  59. runOnce()
  60. } else {
  61. pollForever()
  62. }
  63. }
  64. // No polling: run once and exit.
  65. func runOnce() {
  66. if success, newProfiles := loadNewProfiles(); !success {
  67. if len(newProfiles) > 0 {
  68. klog.Exitf("Not all profiles were successfully loaded. Loaded: %v", newProfiles)
  69. } else {
  70. klog.Exit("Error loading profiles.")
  71. }
  72. } else {
  73. if len(newProfiles) > 0 {
  74. klog.Infof("Successfully loaded profiles: %v", newProfiles)
  75. } else {
  76. klog.Warning("No new profiles found.")
  77. }
  78. }
  79. }
  80. // Poll the directories indefinitely.
  81. func pollForever() {
  82. klog.V(2).Infof("Polling %s every %s", strings.Join(dirs, ", "), poll.String())
  83. pollFn := func() {
  84. _, newProfiles := loadNewProfiles()
  85. if len(newProfiles) > 0 {
  86. klog.V(2).Infof("Successfully loaded profiles: %v", newProfiles)
  87. }
  88. }
  89. pollFn() // Run immediately.
  90. ticker := time.NewTicker(*poll)
  91. for range ticker.C {
  92. pollFn()
  93. }
  94. }
  95. func loadNewProfiles() (success bool, newProfiles []string) {
  96. loadedProfiles, err := getLoadedProfiles()
  97. if err != nil {
  98. klog.Errorf("Error reading loaded profiles: %v", err)
  99. return false, nil
  100. }
  101. success = true
  102. for _, dir := range dirs {
  103. infos, err := ioutil.ReadDir(dir)
  104. if err != nil {
  105. klog.Warningf("Error reading %s: %v", dir, err)
  106. success = false
  107. continue
  108. }
  109. for _, info := range infos {
  110. path := filepath.Join(dir, info.Name())
  111. // If directory, or symlink to a directory, skip it.
  112. resolvedInfo, err := resolveSymlink(dir, info)
  113. if err != nil {
  114. klog.Warningf("Error resolving symlink: %v", err)
  115. continue
  116. }
  117. if resolvedInfo.IsDir() {
  118. // Directory listing is shallow.
  119. klog.V(4).Infof("Skipping directory %s", path)
  120. continue
  121. }
  122. klog.V(4).Infof("Scanning %s for new profiles", path)
  123. profiles, err := getProfileNames(path)
  124. if err != nil {
  125. klog.Warningf("Error reading %s: %v", path, err)
  126. success = false
  127. continue
  128. }
  129. if unloadedProfiles(loadedProfiles, profiles) {
  130. if err := loadProfiles(path); err != nil {
  131. klog.Errorf("Could not load profiles: %v", err)
  132. success = false
  133. continue
  134. }
  135. // Add new profiles to list of loaded profiles.
  136. newProfiles = append(newProfiles, profiles...)
  137. for _, profile := range profiles {
  138. loadedProfiles[profile] = true
  139. }
  140. }
  141. }
  142. }
  143. return success, newProfiles
  144. }
  145. func getProfileNames(path string) ([]string, error) {
  146. cmd := exec.Command(parser, "--names", path)
  147. stderr := &bytes.Buffer{}
  148. cmd.Stderr = stderr
  149. out, err := cmd.Output()
  150. if err != nil {
  151. if stderr.Len() > 0 {
  152. klog.Warning(stderr.String())
  153. }
  154. return nil, fmt.Errorf("error reading profiles from %s: %v", path, err)
  155. }
  156. trimmed := strings.TrimSpace(string(out)) // Remove trailing \n
  157. return strings.Split(trimmed, "\n"), nil
  158. }
  159. func unloadedProfiles(loadedProfiles map[string]bool, profiles []string) bool {
  160. for _, profile := range profiles {
  161. if !loadedProfiles[profile] {
  162. return true
  163. }
  164. }
  165. return false
  166. }
  167. func loadProfiles(path string) error {
  168. cmd := exec.Command(parser, "--verbose", path)
  169. stderr := &bytes.Buffer{}
  170. cmd.Stderr = stderr
  171. out, err := cmd.Output()
  172. klog.V(2).Infof("Loading profiles from %s:\n%s", path, out)
  173. if err != nil {
  174. if stderr.Len() > 0 {
  175. klog.Warning(stderr.String())
  176. }
  177. return fmt.Errorf("error loading profiles from %s: %v", path, err)
  178. }
  179. return nil
  180. }
  181. // If the given fileinfo is a symlink, return the FileInfo of the target. Otherwise, return the
  182. // given fileinfo.
  183. func resolveSymlink(basePath string, info os.FileInfo) (os.FileInfo, error) {
  184. if info.Mode()&os.ModeSymlink == 0 {
  185. // Not a symlink.
  186. return info, nil
  187. }
  188. fpath := filepath.Join(basePath, info.Name())
  189. resolvedName, err := filepath.EvalSymlinks(fpath)
  190. if err != nil {
  191. return nil, fmt.Errorf("error resolving symlink %s: %v", fpath, err)
  192. }
  193. resolvedInfo, err := os.Stat(resolvedName)
  194. if err != nil {
  195. return nil, fmt.Errorf("error calling stat on %s: %v", resolvedName, err)
  196. }
  197. return resolvedInfo, nil
  198. }
  199. // TODO: This is copied from k8s.io/kubernetes/pkg/security/apparmor.getLoadedProfiles.
  200. // Refactor that method to expose it in a reusable way, and delete this version.
  201. func getLoadedProfiles() (map[string]bool, error) {
  202. profilesPath := path.Join(apparmorfs, "profiles")
  203. profilesFile, err := os.Open(profilesPath)
  204. if err != nil {
  205. return nil, fmt.Errorf("failed to open %s: %v", profilesPath, err)
  206. }
  207. defer profilesFile.Close()
  208. profiles := map[string]bool{}
  209. scanner := bufio.NewScanner(profilesFile)
  210. for scanner.Scan() {
  211. profileName := parseProfileName(scanner.Text())
  212. if profileName == "" {
  213. // Unknown line format; skip it.
  214. continue
  215. }
  216. profiles[profileName] = true
  217. }
  218. return profiles, nil
  219. }
  220. // The profiles file is formatted with one profile per line, matching a form:
  221. // namespace://profile-name (mode)
  222. // profile-name (mode)
  223. // Where mode is {enforce, complain, kill}. The "namespace://" is only included for namespaced
  224. // profiles. For the purposes of Kubernetes, we consider the namespace part of the profile name.
  225. func parseProfileName(profileLine string) string {
  226. modeIndex := strings.IndexRune(profileLine, '(')
  227. if modeIndex < 0 {
  228. return ""
  229. }
  230. return strings.TrimSpace(profileLine[:modeIndex])
  231. }