-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathvalidate.go
463 lines (419 loc) · 11.4 KB
/
validate.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"unicode"
"unicode/utf8"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
rspec "github.com/opencontainers/runtime-spec/specs-go"
)
var bundleValidateFlags = []cli.Flag{
cli.StringFlag{Name: "path", Usage: "path to a bundle"},
cli.BoolFlag{Name: "hooks", Usage: "Check specified hooks exist and are executable on the host."},
}
var (
defaultRlimits = []string{
"RLIMIT_CPU",
"RLIMIT_FSIZE",
"RLIMIT_DATA",
"RLIMIT_STACK",
"RLIMIT_CORE",
"RLIMIT_RSS",
"RLIMIT_NPROC",
"RLIMIT_NOFILE",
"RLIMIT_MEMLOCK",
"RLIMIT_AS",
"RLIMIT_LOCKS",
"RLIMIT_SIGPENDING",
"RLIMIT_MSGQUEUE",
"RLIMIT_NICE",
"RLIMIT_RTPRIO",
"RLIMIT_RTTIME",
}
)
var bundleValidateCommand = cli.Command{
Name: "validate",
Usage: "validate a OCI bundle",
Flags: bundleValidateFlags,
Action: func(context *cli.Context) {
inputPath := context.String("path")
if inputPath == "" {
logrus.Fatalf("Bundle path shouldn't be empty")
}
if _, err := os.Stat(inputPath); err != nil {
logrus.Fatal(err)
}
configPath := path.Join(inputPath, "config.json")
content, err := ioutil.ReadFile(configPath)
if err != nil {
logrus.Fatal(err)
}
if !utf8.Valid(content) {
logrus.Fatalf("%q is not encoded in UTF-8", configPath)
}
var spec rspec.Spec
if err = json.Unmarshal(content, &spec); err != nil {
logrus.Fatal(err)
}
rootfsPath := path.Join(inputPath, spec.Root.Path)
if fi, err := os.Stat(rootfsPath); err != nil {
logrus.Fatalf("Cannot find the root path %q", rootfsPath)
} else if !fi.IsDir() {
logrus.Fatalf("The root path %q is not a directory.", rootfsPath)
}
hooksCheck := context.Bool("hooks")
bundleValidate(spec, rootfsPath, hooksCheck)
logrus.Infof("Bundle validation succeeded.")
},
}
func bundleValidate(spec rspec.Spec, rootfs string, hooksCheck bool) {
checkMandatoryField(spec)
checkSemVer(spec.Version)
checkPlatform(spec.Platform)
checkProcess(spec.Process, rootfs)
checkLinux(spec)
checkHooks(spec.Hooks, hooksCheck)
}
func checkSemVer(version string) {
re, _ := regexp.Compile("^(\\d+)?\\.(\\d+)?\\.(\\d+)?$")
if ok := re.Match([]byte(version)); !ok {
logrus.Fatalf("%q is not a valid version format, please read 'SemVer v2.0.0'", version)
}
}
func checkPlatform(platform rspec.Platform) {
validCombins := map[string][]string{
"darwin": {"386", "amd64", "arm", "arm64"},
"dragonfly": {"amd64"},
"freebsd": {"386", "amd64", "arm"},
"linux": {"386", "amd64", "arm", "arm64", "ppc64", "ppc64le", "mips64", "mips64le"},
"netbsd": {"386", "amd64", "arm"},
"openbsd": {"386", "amd64", "arm"},
"plan9": {"386", "amd64"},
"solaris": {"amd64"},
"windows": {"386", "amd64"}}
for os, archs := range validCombins {
if os == platform.OS {
for _, arch := range archs {
if arch == platform.Arch {
return
}
}
logrus.Fatalf("Combination of %q and %q is invalid.", platform.OS, platform.Arch)
}
}
logrus.Fatalf("Operation system %q of the bundle is not supported yet.", platform.OS)
}
func checkHooks(hooks rspec.Hooks, hooksCheck bool) {
checkEventHooks("pre-start", hooks.Prestart, hooksCheck)
checkEventHooks("post-start", hooks.Poststart, hooksCheck)
checkEventHooks("post-stop", hooks.Poststop, hooksCheck)
}
func checkEventHooks(hookType string, hooks []rspec.Hook, hooksCheck bool) {
for _, hook := range hooks {
if !filepath.IsAbs(hook.Path) {
logrus.Fatalf("The %s hook %v: is not absolute path", hookType, hook.Path)
}
if hooksCheck {
fi, err := os.Stat(hook.Path)
if err != nil {
logrus.Fatalf("Cannot find %s hook: %v", hookType, hook.Path)
}
if fi.Mode()&0111 == 0 {
logrus.Fatalf("The %s hook %v: is not executable", hookType, hook.Path)
}
}
for _, env := range hook.Env {
if !envValid(env) {
logrus.Fatalf("Env %q for hook %v is in the invalid form.", env, hook.Path)
}
}
}
}
func checkProcess(process rspec.Process, rootfs string) {
if !path.IsAbs(process.Cwd) {
logrus.Fatalf("cwd %q is not an absolute path", process.Cwd)
}
for _, env := range process.Env {
if !envValid(env) {
logrus.Fatalf("env %q should be in the form of 'key=value'. The left hand side must consist solely of letters, digits, and underscores '_'.", env)
}
}
for index := 0; index < len(process.Capabilities); index++ {
capability := process.Capabilities[index]
if !capValid(capability) {
logrus.Fatalf("capability %q is not valid, man capabilities(7)", process.Capabilities[index])
}
}
for index := 0; index < len(process.Rlimits); index++ {
if !rlimitValid(process.Rlimits[index].Type) {
logrus.Fatalf("rlimit type %q is invalid.", process.Rlimits[index].Type)
}
}
if len(process.ApparmorProfile) > 0 {
profilePath := path.Join(rootfs, "/etc/apparmor.d", process.ApparmorProfile)
_, err := os.Stat(profilePath)
if err != nil {
logrus.Fatal(err)
}
}
}
//Linux only
func checkLinux(spec rspec.Spec) {
utsExists := false
if len(spec.Linux.UIDMappings) > 5 {
logrus.Fatalf("Only 5 UID mappings are allowed (linux kernel restriction).")
}
if len(spec.Linux.GIDMappings) > 5 {
logrus.Fatalf("Only 5 GID mappings are allowed (linux kernel restriction).")
}
for index := 0; index < len(spec.Linux.Namespaces); index++ {
if !namespaceValid(spec.Linux.Namespaces[index]) {
logrus.Fatalf("namespace %v is invalid.", spec.Linux.Namespaces[index])
} else if spec.Linux.Namespaces[index].Type == rspec.UTSNamespace {
utsExists = true
}
}
if spec.Platform.OS == "linux" && !utsExists && spec.Hostname != "" {
logrus.Fatalf("On Linux, hostname requires a new UTS namespace to be specified as well")
}
for index := 0; index < len(spec.Linux.Devices); index++ {
if !deviceValid(spec.Linux.Devices[index]) {
logrus.Fatalf("device %v is invalid.", spec.Linux.Devices[index])
}
}
if spec.Linux.Seccomp != nil {
checkSeccomp(*spec.Linux.Seccomp)
}
switch spec.Linux.RootfsPropagation {
case "":
case "private":
case "rprivate":
case "slave":
case "rslave":
case "shared":
case "rshared":
default:
logrus.Fatalf("rootfsPropagation must be empty or one of \"private|rprivate|slave|rslave|shared|rshared\"")
}
}
func checkSeccomp(s rspec.Seccomp) {
if !seccompActionValid(s.DefaultAction) {
logrus.Fatalf("seccomp defaultAction %q is invalid.", s.DefaultAction)
}
for index := 0; index < len(s.Syscalls); index++ {
if !syscallValid(s.Syscalls[index]) {
logrus.Fatalf("syscall %v is invalid.", s.Syscalls[index])
}
}
for index := 0; index < len(s.Architectures); index++ {
switch s.Architectures[index] {
case rspec.ArchX86:
case rspec.ArchX86_64:
case rspec.ArchX32:
case rspec.ArchARM:
case rspec.ArchAARCH64:
case rspec.ArchMIPS:
case rspec.ArchMIPS64:
case rspec.ArchMIPS64N32:
case rspec.ArchMIPSEL:
case rspec.ArchMIPSEL64:
case rspec.ArchMIPSEL64N32:
default:
logrus.Fatalf("seccomp architecture %q is invalid", s.Architectures[index])
}
}
}
func envValid(env string) bool {
items := strings.Split(env, "=")
if len(items) < 2 {
return false
}
for _, ch := range strings.TrimSpace(items[0]) {
if !unicode.IsDigit(ch) && !unicode.IsLetter(ch) && ch != '_' {
return false
}
}
return true
}
func capValid(capability string) bool {
for _, val := range defaultCaps {
if val == capability {
return true
}
}
return false
}
func rlimitValid(rlimit string) bool {
for _, val := range defaultRlimits {
if val == rlimit {
return true
}
}
return false
}
func namespaceValid(ns rspec.Namespace) bool {
switch ns.Type {
case rspec.PIDNamespace:
case rspec.NetworkNamespace:
case rspec.MountNamespace:
case rspec.IPCNamespace:
case rspec.UTSNamespace:
case rspec.UserNamespace:
default:
return false
}
return true
}
func deviceValid(d rspec.Device) bool {
switch d.Type {
case "b":
case "c":
case "u":
if d.Major <= 0 {
return false
}
if d.Minor <= 0 {
return false
}
case "p":
if d.Major > 0 || d.Minor > 0 {
return false
}
default:
return false
}
return true
}
func seccompActionValid(secc rspec.Action) bool {
switch secc {
case "":
case rspec.ActKill:
case rspec.ActTrap:
case rspec.ActErrno:
case rspec.ActTrace:
case rspec.ActAllow:
default:
return false
}
return true
}
func syscallValid(s rspec.Syscall) bool {
if !seccompActionValid(s.Action) {
return false
}
for index := 0; index < len(s.Args); index++ {
arg := s.Args[index]
switch arg.Op {
case rspec.OpNotEqual:
case rspec.OpLessEqual:
case rspec.OpEqualTo:
case rspec.OpGreaterEqual:
case rspec.OpGreaterThan:
case rspec.OpMaskedEqual:
default:
return false
}
}
return true
}
func isStruct(t reflect.Type) bool {
return t.Kind() == reflect.Struct
}
func isStructPtr(t reflect.Type) bool {
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}
func checkMandatoryUnit(field reflect.Value, tagField reflect.StructField, parent string) ([]string, bool) {
var msgs []string
mandatory := !strings.Contains(tagField.Tag.Get("json"), "omitempty")
switch field.Kind() {
case reflect.Ptr:
if mandatory && field.IsNil() == true {
msgs = append(msgs, fmt.Sprintf("'%s.%s' should not be empty.", parent, tagField.Name))
return msgs, false
}
case reflect.String:
if mandatory && (field.Len() == 0) {
msgs = append(msgs, fmt.Sprintf("'%s.%s' should not be empty.", parent, tagField.Name))
return msgs, false
}
case reflect.Slice:
if mandatory && (field.Len() == 0) {
msgs = append(msgs, fmt.Sprintf("'%s.%s' should not be empty.", parent, tagField.Name))
return msgs, false
}
valid := true
for index := 0; index < field.Len(); index++ {
mValue := field.Index(index)
if mValue.CanInterface() {
if ms, ok := checkMandatory(mValue.Interface()); !ok {
msgs = append(msgs, ms...)
valid = false
}
}
}
return msgs, valid
case reflect.Map:
if mandatory && ((field.IsNil() == true) || (field.Len() == 0)) {
msgs = append(msgs, fmt.Sprintf("'%s.%s' should not be empty.", parent, tagField.Name))
return msgs, false
}
valid := true
keys := field.MapKeys()
for index := 0; index < len(keys); index++ {
mValue := field.MapIndex(keys[index])
if mValue.CanInterface() {
if ms, ok := checkMandatory(mValue.Interface()); !ok {
msgs = append(msgs, ms...)
valid = false
}
}
}
return msgs, valid
default:
}
return nil, true
}
func checkMandatory(obj interface{}) (msgs []string, valid bool) {
objT := reflect.TypeOf(obj)
objV := reflect.ValueOf(obj)
if isStructPtr(objT) {
objT = objT.Elem()
objV = objV.Elem()
} else if !isStruct(objT) {
return nil, true
}
valid = true
for i := 0; i < objT.NumField(); i++ {
t := objT.Field(i).Type
if isStructPtr(t) && objV.Field(i).IsNil() {
if !strings.Contains(objT.Field(i).Tag.Get("json"), "omitempty") {
msgs = append(msgs, fmt.Sprintf("'%s.%s' should not be empty", objT.Name(), objT.Field(i).Name))
valid = false
}
} else if (isStruct(t) || isStructPtr(t)) && objV.Field(i).CanInterface() {
if ms, ok := checkMandatory(objV.Field(i).Interface()); !ok {
msgs = append(msgs, ms...)
valid = false
}
} else {
if ms, ok := checkMandatoryUnit(objV.Field(i), objT.Field(i), objT.Name()); !ok {
msgs = append(msgs, ms...)
valid = false
}
}
}
return msgs, valid
}
func checkMandatoryField(obj interface{}) {
if msgs, valid := checkMandatory(obj); !valid {
logrus.Fatalf("Mandatory information missing: %s.", msgs)
}
}