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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
|
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"github.com/mndrix/tap-go"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/syndtr/gocapability/capability"
"github.com/urfave/cli"
"github.com/opencontainers/runtime-tools/cmd/runtimetest/mount"
rfc2119 "github.com/opencontainers/runtime-tools/error"
"github.com/opencontainers/runtime-tools/specerror"
"github.com/opencontainers/selinux/go-selinux/label"
"golang.org/x/sys/unix"
)
// gitCommit will be the hash that the binary was built from
// and will be populated by the Makefile
var gitCommit = ""
// version will be populated by the Makefile, read from
// VERSION file of the source code.
var version = ""
// errAccess will be used for defining either a read error or a write error
// from any type of files.
var errAccess error
// PrGetNoNewPrivs isn't exposed in Golang so we define it ourselves copying the value from
// the kernel
const PrGetNoNewPrivs = 39
const specConfig = "config.json"
var (
defaultFS = map[string]string{
"/proc": "proc",
"/sys": "sysfs",
"/dev/pts": "devpts",
"/dev/shm": "tmpfs",
}
// NOTE: check if /dev/ptmx is a symlink to /dev/pts/ptmx.
// os.Readlink() returns only a relative path "pts/ptmx" instead of
// an absolute path /dev/pts/ptmx.
defaultSymlinks = map[string]string{
"/dev/fd": "/proc/self/fd",
"/dev/ptmx": "pts/ptmx",
"/dev/stdin": "/proc/self/fd/0",
"/dev/stdout": "/proc/self/fd/1",
"/dev/stderr": "/proc/self/fd/2",
}
defaultDevices = []rspec.LinuxDevice{
{
Path: "/dev/null",
Type: "c",
Major: 1,
Minor: 3,
},
{
Path: "/dev/zero",
Type: "c",
Major: 1,
Minor: 5,
},
{
Path: "/dev/full",
Type: "c",
Major: 1,
Minor: 7,
},
{
Path: "/dev/random",
Type: "c",
Major: 1,
Minor: 8,
},
{
Path: "/dev/urandom",
Type: "c",
Major: 1,
Minor: 9,
},
{
Path: "/dev/tty",
Type: "c",
Major: 5,
Minor: 0,
},
{
Path: "/dev/ptmx",
Type: "c",
Major: 5,
Minor: 2,
},
}
)
type complianceTester struct {
harness *tap.T
complianceLevel rfc2119.Level
}
func (c *complianceTester) Ok(test bool, condition specerror.Code, version string, description string) (rfcError *rfc2119.Error, err error) {
rfcError, err = specerror.NewRFCError(condition, errors.New(description), version)
if err != nil {
return nil, err
}
if test {
c.harness.Pass(description)
} else if rfcError.Level < c.complianceLevel {
c.harness.Skip(1, description)
} else {
c.harness.Fail(description)
}
return rfcError, nil
}
type validator func(config *rspec.Spec) (err error)
func loadSpecConfig(path string) (spec *rspec.Spec, err error) {
configPath := filepath.Join(path, specConfig)
cf, err := os.Open(configPath)
if err != nil {
if os.IsNotExist(err) {
return nil, specerror.NewError(specerror.ConfigInRootBundleDir, err, rspec.Version)
}
return nil, err
}
defer cf.Close()
if err = json.NewDecoder(cf).Decode(&spec); err != nil {
return
}
return spec, nil
}
func (c *complianceTester) validatePosixUser(spec *rspec.Spec) error {
if spec.Process == nil {
return nil
}
uid := uint32(os.Getuid())
c.harness.Ok(uid == spec.Process.User.UID, "has expected user ID")
c.harness.YAML(map[string]uint32{
"expected": spec.Process.User.UID,
"actual": uid,
})
gid := uint32(os.Getgid())
c.harness.Ok(gid == spec.Process.User.GID, "has expected group ID")
c.harness.YAML(map[string]uint32{
"expected": spec.Process.User.GID,
"actual": gid,
})
groups, err := os.Getgroups()
if err != nil {
return err
}
groupsMap := make(map[int]bool)
for _, g := range groups {
groupsMap[g] = true
}
for _, g := range spec.Process.User.AdditionalGids {
c.harness.Ok(groupsMap[int(g)], fmt.Sprintf("has expected additional group ID %v", g))
}
return nil
}
func (c *complianceTester) validateProcess(spec *rspec.Spec) error {
if spec.Process == nil {
c.harness.Skip(1, "process not set")
return nil
}
if spec.Process.Cwd == "" {
c.harness.Skip(1, "process.cwd not set")
} else {
cwd, err := os.Getwd()
if err != nil {
return err
}
c.harness.Ok(cwd == spec.Process.Cwd, "has expected working directory")
c.harness.YAML(map[string]string{
"expected": spec.Process.Cwd,
"actual": cwd,
})
}
for _, env := range spec.Process.Env {
parts := strings.Split(env, "=")
key := parts[0]
expectedValue := parts[1]
actualValue := os.Getenv(key)
c.harness.Ok(expectedValue == actualValue, fmt.Sprintf("has expected environment variable %v", key))
c.harness.YAML(map[string]string{
"variable": key,
"expected": expectedValue,
"actual": actualValue,
})
}
return nil
}
func (c *complianceTester) validateLinuxProcess(spec *rspec.Spec) error {
if spec.Process == nil {
c.harness.Skip(1, "process not set")
return nil
}
cmdlineBytes, err := ioutil.ReadFile("/proc/self/cmdline")
if err != nil {
return err
}
args := bytes.Split(bytes.Trim(cmdlineBytes, "\x00"), []byte("\x00"))
c.harness.Ok(len(args) == len(spec.Process.Args), "has expected number of process arguments")
c.harness.YAML(map[string]interface{}{
"expected": spec.Process.Args,
"actual": args,
})
for i, a := range args {
c.harness.Ok(string(a) == spec.Process.Args[i], fmt.Sprintf("has expected process argument %d", i))
c.harness.YAML(map[string]interface{}{
"index": i,
"expected": spec.Process.Args[i],
"actual": string(a),
})
}
ret, _, errno := syscall.Syscall6(syscall.SYS_PRCTL, PrGetNoNewPrivs, 0, 0, 0, 0, 0)
if errno != 0 {
return errno
}
noNewPrivileges := ret == 1
c.harness.Ok(spec.Process.NoNewPrivileges == noNewPrivileges, "has expected noNewPrivileges")
return nil
}
func (c *complianceTester) validateCapabilities(spec *rspec.Spec) error {
if spec.Process == nil || spec.Process.Capabilities == nil {
c.harness.Skip(1, "process.capabilities not set")
return nil
}
last := capability.CAP_LAST_CAP
// workaround for RHEL6 which has no /proc/sys/kernel/cap_last_cap
if last == capability.Cap(63) {
last = capability.CAP_BLOCK_SUSPEND
}
processCaps, err := capability.NewPid(0)
if err != nil {
return err
}
for _, capType := range []struct {
capType capability.CapType
config []string
}{
{
capType: capability.BOUNDING,
config: spec.Process.Capabilities.Bounding,
},
{
capType: capability.EFFECTIVE,
config: spec.Process.Capabilities.Effective,
},
{
capType: capability.INHERITABLE,
config: spec.Process.Capabilities.Inheritable,
},
{
capType: capability.PERMITTED,
config: spec.Process.Capabilities.Permitted,
},
{
capType: capability.AMBIENT,
config: spec.Process.Capabilities.Ambient,
},
} {
expectedCaps := make(map[string]bool)
for _, ec := range capType.config {
expectedCaps[ec] = true
}
for _, cap := range capability.List() {
if cap > last {
continue
}
capKey := fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String()))
expectedSet := expectedCaps[capKey]
actuallySet := processCaps.Get(capType.capType, cap)
if expectedSet {
c.harness.Ok(actuallySet, fmt.Sprintf("expected %s capability %v set", capType.capType, capKey))
} else {
c.harness.Ok(!actuallySet, fmt.Sprintf("unexpected %s capability %v not set", capType.capType, capKey))
}
}
}
return nil
}
func (c *complianceTester) validateHostname(spec *rspec.Spec) error {
if spec.Hostname == "" {
c.harness.Skip(1, "hostname not set")
return nil
}
hostname, err := os.Hostname()
if err != nil {
return err
}
c.harness.Ok(spec.Hostname == hostname, "has expected hostname")
c.harness.YAML(map[string]string{
"expected": spec.Hostname,
"actual": hostname,
})
return nil
}
func (c *complianceTester) validateRlimits(spec *rspec.Spec) error {
if spec.Process == nil {
c.harness.Skip(1, "process.rlimits not set")
return nil
}
for _, r := range spec.Process.Rlimits {
rl, err := strToRlimit(r.Type)
if err != nil {
return err
}
var rlimit syscall.Rlimit
if err := syscall.Getrlimit(rl, &rlimit); err != nil {
return err
}
rfcError, err := c.Ok(rlimit.Cur == r.Soft, specerror.PosixProcRlimitsSoftMatchCur, spec.Version, fmt.Sprintf("has expected soft %v", r.Type))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"type": r.Type,
"expected": r.Soft,
"actual": rlimit.Cur,
})
rfcError, err = c.Ok(rlimit.Max == r.Hard, specerror.PosixProcRlimitsHardMatchMax, spec.Version, fmt.Sprintf("has expected hard %v", r.Type))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"type": r.Type,
"expected": r.Hard,
"actual": rlimit.Max,
})
}
return nil
}
func (c *complianceTester) validateSysctls(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.Sysctl == nil {
c.harness.Skip(1, "linux.sysctl not set")
return nil
}
for k, v := range spec.Linux.Sysctl {
keyPath := filepath.Join("/proc/sys", strings.Replace(k, ".", "/", -1))
vBytes, err := ioutil.ReadFile(keyPath)
if err != nil {
return err
}
value := strings.TrimSpace(string(bytes.Trim(vBytes, "\x00")))
c.harness.Ok(value == v, fmt.Sprintf("has expected sysctl %v", k))
c.harness.YAML(map[string]string{
"sysctl": k,
"expected": v,
"actual": value,
})
}
return nil
}
func testReadAccess(path string) (readable bool, err error) {
fi, err := os.Stat(path)
if err != nil {
return false, err
}
// Check for readability in case of regular files, character device, or
// directory. Although the runtime spec does not mandate the type of
// masked files, we should check its Mode explicitly. A masked file
// could be represented as a character file (/dev/null), which is the
// case for runtimes like runc.
switch fi.Mode() & os.ModeType {
case 0, os.ModeDevice | os.ModeCharDevice:
return testFileReadAccess(path)
case os.ModeDir:
return testDirectoryReadAccess(path)
}
errAccess = fmt.Errorf("cannot test read access for %q (mode %d)", path, fi.Mode())
return false, errAccess
}
func testDirectoryReadAccess(path string) (readable bool, err error) {
files, err := ioutil.ReadDir(path)
if err == io.EOF || len(files) == 0 {
// Our validation/ tests only use non-empty directories for read-access
// tests. So if we get an EOF on the first read, the runtime did
// successfully block readability. So it should not be considered as test
// failure, it just means that the test program successfully assessed
// that the directory is not readable.
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
func testFileReadAccess(path string) (readable bool, err error) {
f, err := os.Open(path)
if err != nil {
return false, nil
}
defer f.Close()
b := make([]byte, 1)
_, err = f.Read(b)
if err == nil {
return true, nil
} else if err == io.EOF {
// Our validation/ tests only use non-empty files for read-access
// tests. So if we get an EOF on the first read, the runtime did
// successfully block readability.
return false, nil
}
return false, err
}
func testWriteAccess(path string) (writable bool, err error) {
fi, err := os.Stat(path)
if err != nil {
return false, err
}
// Check for writability in case of regular files, character device, or
// directory. Although the runtime spec does not mandate the type of
// masked files, we should check its Mode explicitly. A masked file
// could be represented as a character file (/dev/null), which is the
// case for runtimes like runc.
switch fi.Mode() & os.ModeType {
case 0, os.ModeDevice | os.ModeCharDevice:
return testFileWriteAccess(path)
case os.ModeDir:
return testDirectoryWriteAccess(path)
}
errAccess = fmt.Errorf("cannot test write access for %q (mode %d)", path, fi.Mode())
return false, errAccess
}
func testDirectoryWriteAccess(path string) (writable bool, err error) {
tmpfile, err := ioutil.TempFile(path, "Test")
if err != nil {
return false, nil
}
tmpfile.Close()
return true, os.RemoveAll(filepath.Join(path, tmpfile.Name()))
}
func testFileWriteAccess(path string) (readable bool, err error) {
err = ioutil.WriteFile(path, []byte("a"), 0644)
if err == nil {
return true, nil
}
return false, nil
}
func (c *complianceTester) validateRootFS(spec *rspec.Spec) error {
if spec.Root == nil {
c.harness.Skip(1, "root not set")
return nil
}
writable, err := testDirectoryWriteAccess("/")
if err != nil {
return err
}
if spec.Root.Readonly {
rfcError, err := c.Ok(!writable, specerror.RootReadonlyImplement, spec.Version, "root filesystem is readonly")
if err != nil {
return err
}
c.harness.YAML(map[string]string{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
})
} else if !writable {
c.harness.Skip(1, "root.readonly is false but the root filesystem is still not writable")
}
return nil
}
func (c *complianceTester) validateRootfsPropagation(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.RootfsPropagation == "" {
c.harness.Skip(1, "linux.rootfsPropagation not set")
return nil
}
targetDir, err := ioutil.TempDir("/", "target")
if err != nil {
return err
}
defer os.RemoveAll(targetDir)
switch spec.Linux.RootfsPropagation {
case "shared", "slave", "private":
mountDir, err := ioutil.TempDir("/", "mount")
if err != nil {
return err
}
defer os.RemoveAll(mountDir)
testDir, err := ioutil.TempDir("/", "test")
if err != nil {
return err
}
defer os.RemoveAll(testDir)
tmpfile, err := ioutil.TempFile(testDir, "example")
if err != nil {
return err
}
defer os.Remove(tmpfile.Name())
if err := unix.Mount("/", targetDir, "", unix.MS_BIND|unix.MS_REC, ""); err != nil {
return err
}
defer unix.Unmount(targetDir, unix.MNT_DETACH)
if err := unix.Mount(testDir, mountDir, "", unix.MS_BIND|unix.MS_REC, ""); err != nil {
return err
}
defer unix.Unmount(mountDir, unix.MNT_DETACH)
targetFile := filepath.Join(targetDir, filepath.Join(mountDir, filepath.Base(tmpfile.Name())))
var exposed bool
_, err = os.Stat(targetFile)
if os.IsNotExist(err) {
exposed = false
} else if err != nil {
return err
} else {
exposed = true
}
if spec.Linux.RootfsPropagation == "shared" {
c.harness.Ok(exposed, fmt.Sprintf("shared root propagation exposes %q", targetFile))
} else {
c.harness.Ok(
!exposed,
fmt.Sprintf("%s root propagation does not expose %q", spec.Linux.RootfsPropagation, targetFile),
)
}
case "unbindable":
err = unix.Mount("/", targetDir, "", unix.MS_BIND|unix.MS_REC, "")
if err == syscall.EINVAL {
c.harness.Pass("root propagation is unbindable")
return nil
} else if err != nil {
return err
}
defer unix.Unmount(targetDir, unix.MNT_DETACH)
c.harness.Fail("root propagation is unbindable")
return nil
default:
c.harness.Skip(1, fmt.Sprintf("unrecognized linux.rootfsPropagation %s", spec.Linux.RootfsPropagation))
}
return nil
}
func (c *complianceTester) validateDefaultFS(spec *rspec.Spec) error {
mountInfos, err := mount.GetMounts()
if err != nil {
return nil
}
mountsMap := make(map[string]string)
for _, mountInfo := range mountInfos {
mountsMap[mountInfo.Mountpoint] = mountInfo.Fstype
}
for fs, fstype := range defaultFS {
rfcError, err := c.Ok(mountsMap[fs] == fstype, specerror.DefaultFilesystems, spec.Version, fmt.Sprintf("mount %v has expected type", fs))
if err != nil {
return err
}
c.harness.YAML(map[string]string{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"mount": fs,
"expected": fstype,
"actual": mountsMap[fs],
})
}
return nil
}
func (c *complianceTester) validateLinuxDevices(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.Devices == nil {
c.harness.Skip(1, "linux.devices is not set")
return nil
}
for i, device := range spec.Linux.Devices {
err := c.validateDevice(
&device,
specerror.DevicesAvailable,
spec.Version,
fmt.Sprintf("%q (linux.devices[%d])", device.Path, i))
if err != nil {
return err
}
}
return nil
}
func (c *complianceTester) validateDevice(device *rspec.LinuxDevice, condition specerror.Code, version string, description string) (err error) {
var exists bool
fi, err := os.Stat(device.Path)
if os.IsNotExist(err) {
exists = false
} else if err != nil {
return err
} else {
exists = true
}
rfcError, err := c.Ok(exists, condition, version, fmt.Sprintf("has a file at %s", description))
if err != nil {
return err
}
c.harness.YAML(map[string]string{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": device.Path,
})
if !exists {
return nil
}
fStat, ok := fi.Sys().(*syscall.Stat_t)
if !ok {
return fmt.Errorf("could not convert to syscall.Stat_t: %v", fi.Sys())
}
expectedType := device.Type
if expectedType == "u" {
expectedType = "c"
}
var devType string
switch fStat.Mode & syscall.S_IFMT {
case syscall.S_IFCHR:
devType = "c"
case syscall.S_IFBLK:
devType = "b"
case syscall.S_IFIFO:
devType = "p"
default:
devType = "unmatched"
}
rfcError, err = c.Ok(devType == expectedType, condition, version, fmt.Sprintf("%s has the expected type", description))
if err != nil {
return err
}
c.harness.YAML(map[string]string{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": device.Path,
"expected": expectedType,
"actual": devType,
})
if devType != expectedType {
return nil
}
if devType != "p" {
dev := fStat.Rdev
major := (dev >> 8) & 0xfff
minor := (dev & 0xff) | ((dev >> 12) & 0xfff00)
rfcError, err = c.Ok(int64(major) == device.Major, condition, version, fmt.Sprintf("%s has the expected major ID", description))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": device.Path,
"expected": device.Major,
"actual": major,
})
rfcError, err = c.Ok(int64(minor) == device.Minor, condition, version, fmt.Sprintf("%s has the expected minor ID", description))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": device.Path,
"expected": device.Minor,
"actual": minor,
})
}
if device.FileMode == nil {
c.harness.Skip(1, fmt.Sprintf("%s has unconfigured permissions", description))
} else {
expectedPerm := *device.FileMode & os.ModePerm
actualPerm := fi.Mode() & os.ModePerm
rfcError, err = c.Ok(actualPerm == expectedPerm, condition, version, fmt.Sprintf("%s has the expected permissions", description))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": device.Path,
"expected": expectedPerm,
"actual": actualPerm,
})
}
if description == "/dev/console (default device)" {
c.harness.Todo().Fail("we need the major/minor from the controlling TTY")
return nil
}
if device.UID == nil {
c.harness.Skip(1, fmt.Sprintf("%s has an unconfigured user ID", description))
} else {
rfcError, err = c.Ok(fStat.Uid == *device.UID, condition, version, fmt.Sprintf("%s has the expected user ID", description))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": device.Path,
"expected": *device.UID,
"actual": fStat.Uid,
})
}
if device.GID == nil {
c.harness.Skip(1, fmt.Sprintf("%s has an unconfigured group ID", description))
} else {
rfcError, err = c.Ok(fStat.Gid == *device.GID, condition, version, fmt.Sprintf("%s has the expected group ID", description))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": device.Path,
"expected": *device.GID,
"actual": fStat.Gid,
})
}
return nil
}
func (c *complianceTester) validateDefaultSymlinks(spec *rspec.Spec) error {
for symlink, dest := range defaultSymlinks {
var exists bool
fi, err := os.Lstat(symlink)
if os.IsNotExist(err) {
exists = false
} else if err != nil {
return err
} else {
exists = true
}
rfcError, err := c.Ok(exists, specerror.DefaultRuntimeLinuxSymlinks, spec.Version, fmt.Sprintf("has a file at default symlink path %q", symlink))
if err != nil {
return err
}
c.harness.YAML(map[string]string{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": symlink,
})
if !exists {
continue
}
isSymlink := fi.Mode()&os.ModeType == os.ModeSymlink
rfcError, err = c.Ok(
isSymlink,
specerror.DefaultRuntimeLinuxSymlinks,
spec.Version,
fmt.Sprintf("file at default symlink path %q is a symlink", symlink))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": symlink,
"mode": fi.Mode(),
})
if !isSymlink {
continue
}
realDest, err := os.Readlink(symlink)
if err != nil {
return err
}
rfcError, err = c.Ok(
realDest == dest,
specerror.DefaultRuntimeLinuxSymlinks,
spec.Version,
fmt.Sprintf("symlink at default symlink path %q has the expected target", symlink))
if err != nil {
return err
}
c.harness.YAML(map[string]string{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"path": symlink,
"expected": dest,
"actual": realDest,
})
}
return nil
}
func (c *complianceTester) validateDefaultDevices(spec *rspec.Spec) error {
if spec.Process != nil && spec.Process.Terminal {
defaultDevices = append(defaultDevices, rspec.LinuxDevice{
Path: "/dev/console",
Type: "c",
// FIXME: get the major/minor from the controlling TTY
})
}
for _, device := range defaultDevices {
err := c.validateDevice(
&device,
specerror.DefaultDevices,
spec.Version,
fmt.Sprintf("%s (default device)", device.Path))
if err != nil {
return err
}
}
return nil
}
func (c *complianceTester) validateMaskedPaths(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.MaskedPaths == nil {
c.harness.Skip(1, "linux.maskedPaths not set")
return nil
}
for _, maskedPath := range spec.Linux.MaskedPaths {
readable, err := testReadAccess(maskedPath)
if err != nil && !os.IsNotExist(err) && err != errAccess {
return err
}
c.harness.Ok(!readable, fmt.Sprintf("cannot read masked path %q", maskedPath))
}
return nil
}
func (c *complianceTester) validateSeccomp(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.Seccomp == nil {
c.harness.Skip(1, "linux.seccomp not set")
return nil
}
for _, sys := range spec.Linux.Seccomp.Syscalls {
if sys.Action == "SCMP_ACT_ERRNO" {
for _, name := range sys.Names {
if name == "getcwd" {
_, err := os.Getwd()
if err == nil {
c.harness.Skip(1, "getcwd did not return an error")
}
} else {
c.harness.Skip(1, fmt.Sprintf("%s syscall returns errno", name))
}
}
} else {
c.harness.Skip(1, fmt.Sprintf("syscall action %s", sys.Action))
}
}
return nil
}
func (c *complianceTester) validateROPaths(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.ReadonlyPaths == nil {
c.harness.Skip(1, "linux.readonlyPaths not set")
return nil
}
for i, path := range spec.Linux.ReadonlyPaths {
readable, err := testReadAccess(path)
if err != nil && err != errAccess {
return err
}
if !readable {
c.harness.Skip(1, fmt.Sprintf("%q (linux.readonlyPaths[%d]) is not readable", path, i))
}
writable, err := testWriteAccess(path)
if err != nil && !os.IsNotExist(err) && err != errAccess {
return err
}
c.harness.Ok(!writable, fmt.Sprintf("%q (linux.readonlyPaths[%d]) is not writable", path, i))
}
return nil
}
func (c *complianceTester) validateOOMScoreAdj(spec *rspec.Spec) error {
if spec.Process == nil || spec.Process.OOMScoreAdj == nil {
c.harness.Skip(1, "process.oomScoreAdj not set")
return nil
}
expected := *spec.Process.OOMScoreAdj
f, err := os.Open("/proc/self/oom_score_adj")
if err != nil {
return err
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
err := s.Err()
if err != nil {
return err
}
text := strings.TrimSpace(s.Text())
actual, err := strconv.Atoi(text)
if err != nil {
return err
}
rfcError, err := c.Ok(actual == expected, specerror.LinuxProcOomScoreAdjSet, spec.Version, fmt.Sprintf("has expected OOM score adjustment"))
if err != nil {
return err
}
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"expected": expected,
"actual": actual,
})
}
return nil
}
func getIDMappings(path string) ([]rspec.LinuxIDMapping, error) {
var idMaps []rspec.LinuxIDMapping
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
if err := s.Err(); err != nil {
return nil, err
}
idMap := strings.Fields(strings.TrimSpace(s.Text()))
if len(idMap) == 3 {
// "man 7 user_namespaces" explains the format of uid_map and gid_map:
// <containerID> <hostID> <mapSize>
containerID, err := strconv.ParseUint(idMap[0], 0, 32)
if err != nil {
return nil, err
}
hostID, err := strconv.ParseUint(idMap[1], 0, 32)
if err != nil {
return nil, err
}
mapSize, err := strconv.ParseUint(idMap[2], 0, 32)
if err != nil {
return nil, err
}
idMaps = append(idMaps, rspec.LinuxIDMapping{HostID: uint32(hostID), ContainerID: uint32(containerID), Size: uint32(mapSize)})
} else {
return nil, fmt.Errorf("invalid format in %v", path)
}
}
return idMaps, nil
}
func (c *complianceTester) validateIDMappings(mappings []rspec.LinuxIDMapping, path string, property string) error {
if len(mappings) == 0 {
c.harness.Skip(1, fmt.Sprintf("%s not set", property))
return nil
}
idMaps, err := getIDMappings(path)
if err != nil {
return err
}
c.harness.Ok(len(idMaps) == len(mappings), fmt.Sprintf("%s has expected number of mappings", path))
c.harness.YAML(map[string]interface{}{
"expected": mappings,
"actual": idMaps,
})
for _, v := range mappings {
exist := false
for _, cv := range idMaps {
if v.HostID == cv.HostID && v.ContainerID == cv.ContainerID && v.Size == cv.Size {
exist = true
break
}
}
c.harness.Ok(exist, fmt.Sprintf("%s has expected mapping %v", path, v))
}
return nil
}
func (c *complianceTester) validateUIDMappings(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.UIDMappings == nil {
c.harness.Skip(1, "linux.uidMappings not set")
return nil
}
return c.validateIDMappings(spec.Linux.UIDMappings, "/proc/self/uid_map", "linux.uidMappings")
}
func (c *complianceTester) validateGIDMappings(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.GIDMappings == nil {
c.harness.Skip(1, "linux.gidMappings not set")
return nil
}
return c.validateIDMappings(spec.Linux.GIDMappings, "/proc/self/gid_map", "linux.gidMappings")
}
func mountMatch(configMount rspec.Mount, sysMount *mount.Info) error {
sys := rspec.Mount{
Destination: sysMount.Mountpoint,
Type: sysMount.Fstype,
Source: sysMount.Source,
}
if filepath.Clean(configMount.Destination) != sys.Destination {
return fmt.Errorf("mount destination expected: %v, actual: %v", configMount.Destination, sys.Destination)
}
isBind := false
for _, opt := range configMount.Options {
if opt == "bind" || opt == "rbind" {
isBind = true
break
}
}
// Type is an optional field in the spec: only check if it is set
if configMount.Type != "" && configMount.Type != sys.Type {
return fmt.Errorf("mount %v type expected: %v, actual: %v", configMount.Destination, configMount.Type, sys.Type)
}
// For bind mounts, the source is not the block device but the path on the host that is being bind mounted.
// sysMount.Root is that path.
if isBind {
// Source is an optional field in the spec: only check if it is set
// We only test the base name here, in case the tests are being run in a chroot environment
if configMount.Source != "" && filepath.Base(configMount.Source) != filepath.Base(sysMount.Root) {
return fmt.Errorf("mount %v source expected: %v, actual: %v", configMount.Destination, filepath.Base(configMount.Source), filepath.Base(sysMount.Root))
}
} else {
// Source is an optional field in the spec: only check if it is set
if configMount.Source != "" && filepath.Clean(configMount.Source) != sys.Source {
return fmt.Errorf("mount %v source expected: %v, actual: %v", configMount.Destination, configMount.Source, sys.Source)
}
}
return nil
}
func (c *complianceTester) validatePosixMounts(spec *rspec.Spec) error {
if spec.Mounts == nil {
c.harness.Skip(1, "mounts not set")
return nil
}
mountInfos, err := mount.GetMounts()
if err != nil {
return err
}
var mountErrs error
var configSys = make(map[int]int)
var consumedSys = make(map[int]bool)
highestMatchedConfig := -1
var j = 0
for i, configMount := range spec.Mounts {
if configMount.Type == "bind" || configMount.Type == "rbind" {
c.harness.Todo().Fail("we need an (r)bind spec to test against")
continue
}
foundInOrder := false
foundOutOfOrder := false
for k, sysMount := range mountInfos[j:] {
if err := mountMatch(configMount, sysMount); err == nil {
foundInOrder = true
j += k + 1
configSys[i] = j - 1
consumedSys[j-1] = true
if j > configSys[highestMatchedConfig] {
highestMatchedConfig = i
}
break
}
}
if err != nil {
return err
}
if !foundInOrder {
if j > 0 {
for k, sysMount := range mountInfos[:j-1] {
if _, ok := consumedSys[k]; ok {
continue
}
if err := mountMatch(configMount, sysMount); err == nil {
foundOutOfOrder = true
break
}
}
}
}
var rfcError *rfc2119.Error
if !foundInOrder && !foundOutOfOrder {
rfcError, err = c.Ok(false, specerror.MountsInOrder, spec.Version, fmt.Sprintf("mounts[%d] (%s) found", i, configMount.Destination))
} else {
rfcError, err = c.Ok(foundInOrder, specerror.MountsInOrder, spec.Version, fmt.Sprintf("mounts[%d] (%s) found in order", i, configMount.Destination))
c.harness.YAML(map[string]interface{}{
"level": rfcError.Level.String(),
"reference": rfcError.Reference,
"config": configMount,
"indexConfig": i,
"indexSystem": configSys[i],
"earlier": map[string]interface{}{
"config": spec.Mounts[highestMatchedConfig],
"indexConfig": highestMatchedConfig,
"indexSystem": configSys[highestMatchedConfig],
},
})
}
}
return mountErrs
}
func (c *complianceTester) validateApparmorProfile(spec *rspec.Spec) error {
if spec.Process == nil || spec.Process.ApparmorProfile == "" {
c.harness.Skip(1, "process.ApparmorProfile not set")
return nil
}
profilePath := filepath.Join(spec.Root.Path, "/etc/apparmor.d", spec.Process.ApparmorProfile)
_, err := os.Stat(profilePath)
c.harness.Ok(err != nil, "has expected apparmorProfile")
return nil
}
func (c *complianceTester) validateMountLabel(spec *rspec.Spec) error {
if spec.Linux == nil || spec.Linux.MountLabel == "" {
c.harness.Skip(1, "linux.mountlabel not set")
return nil
}
for _, mount := range spec.Mounts {
isBind := false
for _, opt := range mount.Options {
if opt == "bind" || opt == "rbind" {
isBind = true
break
}
}
if !isBind {
continue
}
fileLabel, err := label.FileLabel(mount.Destination)
if err != nil {
return fmt.Errorf("Failed to get mountLabel of %v", mount.Destination)
}
c.harness.Ok(spec.Linux.MountLabel == fileLabel, "has expected mountlabel")
c.harness.YAML(map[string]string{
"expected": spec.Linux.MountLabel,
"actual": fileLabel,
})
}
return nil
}
func run(context *cli.Context) error {
logLevelString := context.String("log-level")
logLevel, err := logrus.ParseLevel(logLevelString)
if err != nil {
return err
}
logrus.SetLevel(logLevel)
platform := runtime.GOOS
if platform != "linux" && platform != "solaris" && platform != "windows" {
return fmt.Errorf("runtime-tools has not implemented testing for your platform %q, because the spec has nothing to say about it", platform)
}
inputPath := context.String("path")
spec, err := loadSpecConfig(inputPath)
if err != nil {
return err
}
complianceLevelString := context.String("compliance-level")
complianceLevel, err := rfc2119.ParseLevel(complianceLevelString)
if err != nil {
complianceLevel = rfc2119.Must
logrus.Warningf("%s, using 'MUST' by default.", err.Error())
}
c := &complianceTester{
harness: tap.New(),
complianceLevel: complianceLevel,
}
c.harness.Header(0)
defaultValidations := []validator{
c.validateRootFS,
c.validateHostname,
c.validateProcess,
}
posixValidations := []validator{
c.validatePosixMounts,
c.validatePosixUser,
c.validateRlimits,
}
linuxValidations := []validator{
c.validateCapabilities,
c.validateDefaultSymlinks,
c.validateDefaultFS,
c.validateDefaultDevices,
c.validateLinuxDevices,
c.validateLinuxProcess,
c.validateMaskedPaths,
c.validateOOMScoreAdj,
c.validateSeccomp,
c.validateROPaths,
c.validateRootfsPropagation,
c.validateSysctls,
c.validateUIDMappings,
c.validateGIDMappings,
c.validateMountLabel,
c.validateApparmorProfile,
}
validations := defaultValidations
if platform == "linux" {
validations = append(validations, posixValidations...)
validations = append(validations, linuxValidations...)
} else if platform == "solaris" {
validations = append(validations, posixValidations...)
}
for _, validation := range validations {
err := validation(spec)
if err != nil {
return err
}
}
c.harness.AutoPlan()
return nil
}
func main() {
app := cli.NewApp()
app.Name = "runtimetest"
if gitCommit != "" {
app.Version = fmt.Sprintf("%s, commit: %s", version, gitCommit)
} else {
app.Version = version
}
app.Usage = "Compare the environment with an OCI configuration"
app.Description = "runtimetest compares its current environment with an OCI runtime configuration read from config.json in its current working directory. The tests are fairly generic and cover most configurations used by the runtime validation suite, but there are corner cases where a container launched by a valid runtime would not satisfy runtimetest."
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "log-level",
Value: "error",
Usage: "Log level (panic, fatal, error, warn, info, or debug)",
},
cli.StringFlag{
Name: "path",
Value: ".",
Usage: "Path to the configuration",
},
cli.StringFlag{
Name: "compliance-level",
Value: "must",
Usage: "Compliance level (may, should or must)",
},
}
app.Action = run
if err := app.Run(os.Args); err != nil {
logrus.Fatal(err)
}
}
|