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