github.com/megatontech/mynoteforgo@v0.0.0-20200507084910-5d0c6ea6e890/源码/syscall/exec_linux_test.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build linux 6 7 package syscall_test 8 9 import ( 10 "flag" 11 "fmt" 12 "internal/testenv" 13 "io" 14 "io/ioutil" 15 "os" 16 "os/exec" 17 "os/user" 18 "path/filepath" 19 "runtime" 20 "strconv" 21 "strings" 22 "syscall" 23 "testing" 24 "unsafe" 25 ) 26 27 func isDocker() bool { 28 _, err := os.Stat("/.dockerenv") 29 return err == nil 30 } 31 32 func isLXC() bool { 33 return os.Getenv("container") == "lxc" 34 } 35 36 func skipInContainer(t *testing.T) { 37 if isDocker() { 38 t.Skip("skip this test in Docker container") 39 } 40 if isLXC() { 41 t.Skip("skip this test in LXC container") 42 } 43 } 44 45 // Check if we are in a chroot by checking if the inode of / is 46 // different from 2 (there is no better test available to non-root on 47 // linux). 48 func isChrooted(t *testing.T) bool { 49 root, err := os.Stat("/") 50 if err != nil { 51 t.Fatalf("cannot stat /: %v", err) 52 } 53 return root.Sys().(*syscall.Stat_t).Ino != 2 54 } 55 56 func checkUserNS(t *testing.T) { 57 skipInContainer(t) 58 if _, err := os.Stat("/proc/self/ns/user"); err != nil { 59 if os.IsNotExist(err) { 60 t.Skip("kernel doesn't support user namespaces") 61 } 62 if os.IsPermission(err) { 63 t.Skip("unable to test user namespaces due to permissions") 64 } 65 t.Fatalf("Failed to stat /proc/self/ns/user: %v", err) 66 } 67 if isChrooted(t) { 68 // create_user_ns in the kernel (see 69 // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/kernel/user_namespace.c) 70 // forbids the creation of user namespaces when chrooted. 71 t.Skip("cannot create user namespaces when chrooted") 72 } 73 // On some systems, there is a sysctl setting. 74 if os.Getuid() != 0 { 75 data, errRead := ioutil.ReadFile("/proc/sys/kernel/unprivileged_userns_clone") 76 if errRead == nil && data[0] == '0' { 77 t.Skip("kernel prohibits user namespace in unprivileged process") 78 } 79 } 80 // On Centos 7 make sure they set the kernel parameter user_namespace=1 81 // See issue 16283 and 20796. 82 if _, err := os.Stat("/sys/module/user_namespace/parameters/enable"); err == nil { 83 buf, _ := ioutil.ReadFile("/sys/module/user_namespace/parameters/enabled") 84 if !strings.HasPrefix(string(buf), "Y") { 85 t.Skip("kernel doesn't support user namespaces") 86 } 87 } 88 89 // On Centos 7.5+, user namespaces are disabled if user.max_user_namespaces = 0 90 if _, err := os.Stat("/proc/sys/user/max_user_namespaces"); err == nil { 91 buf, errRead := ioutil.ReadFile("/proc/sys/user/max_user_namespaces") 92 if errRead == nil && buf[0] == '0' { 93 t.Skip("kernel doesn't support user namespaces") 94 } 95 } 96 97 // When running under the Go continuous build, skip tests for 98 // now when under Kubernetes. (where things are root but not quite) 99 // Both of these are our own environment variables. 100 // See Issue 12815. 101 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 102 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 103 } 104 } 105 106 func whoamiCmd(t *testing.T, uid, gid int, setgroups bool) *exec.Cmd { 107 checkUserNS(t) 108 cmd := exec.Command("whoami") 109 cmd.SysProcAttr = &syscall.SysProcAttr{ 110 Cloneflags: syscall.CLONE_NEWUSER, 111 UidMappings: []syscall.SysProcIDMap{ 112 {ContainerID: 0, HostID: uid, Size: 1}, 113 }, 114 GidMappings: []syscall.SysProcIDMap{ 115 {ContainerID: 0, HostID: gid, Size: 1}, 116 }, 117 GidMappingsEnableSetgroups: setgroups, 118 } 119 return cmd 120 } 121 122 func testNEWUSERRemap(t *testing.T, uid, gid int, setgroups bool) { 123 cmd := whoamiCmd(t, uid, gid, setgroups) 124 out, err := cmd.CombinedOutput() 125 if err != nil { 126 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 127 } 128 sout := strings.TrimSpace(string(out)) 129 want := "root" 130 if sout != want { 131 t.Fatalf("whoami = %q; want %q", out, want) 132 } 133 } 134 135 func TestCloneNEWUSERAndRemapRootDisableSetgroups(t *testing.T) { 136 if os.Getuid() != 0 { 137 t.Skip("skipping root only test") 138 } 139 testNEWUSERRemap(t, 0, 0, false) 140 } 141 142 func TestCloneNEWUSERAndRemapRootEnableSetgroups(t *testing.T) { 143 if os.Getuid() != 0 { 144 t.Skip("skipping root only test") 145 } 146 testNEWUSERRemap(t, 0, 0, true) 147 } 148 149 func TestCloneNEWUSERAndRemapNoRootDisableSetgroups(t *testing.T) { 150 if os.Getuid() == 0 { 151 t.Skip("skipping unprivileged user only test") 152 } 153 testNEWUSERRemap(t, os.Getuid(), os.Getgid(), false) 154 } 155 156 func TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups(t *testing.T) { 157 if os.Getuid() == 0 { 158 t.Skip("skipping unprivileged user only test") 159 } 160 cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), true) 161 err := cmd.Run() 162 if err == nil { 163 t.Skip("probably old kernel without security fix") 164 } 165 if !os.IsPermission(err) { 166 t.Fatalf("Unprivileged gid_map rewriting with GidMappingsEnableSetgroups must fail") 167 } 168 } 169 170 func TestEmptyCredGroupsDisableSetgroups(t *testing.T) { 171 cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), false) 172 cmd.SysProcAttr.Credential = &syscall.Credential{} 173 if err := cmd.Run(); err != nil { 174 t.Fatal(err) 175 } 176 } 177 178 func TestUnshare(t *testing.T) { 179 skipInContainer(t) 180 // Make sure we are running as root so we have permissions to use unshare 181 // and create a network namespace. 182 if os.Getuid() != 0 { 183 t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace") 184 } 185 186 // When running under the Go continuous build, skip tests for 187 // now when under Kubernetes. (where things are root but not quite) 188 // Both of these are our own environment variables. 189 // See Issue 12815. 190 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 191 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 192 } 193 194 path := "/proc/net/dev" 195 if _, err := os.Stat(path); err != nil { 196 if os.IsNotExist(err) { 197 t.Skip("kernel doesn't support proc filesystem") 198 } 199 if os.IsPermission(err) { 200 t.Skip("unable to test proc filesystem due to permissions") 201 } 202 t.Fatal(err) 203 } 204 if _, err := os.Stat("/proc/self/ns/net"); err != nil { 205 if os.IsNotExist(err) { 206 t.Skip("kernel doesn't support net namespace") 207 } 208 t.Fatal(err) 209 } 210 211 orig, err := ioutil.ReadFile(path) 212 if err != nil { 213 t.Fatal(err) 214 } 215 origLines := strings.Split(strings.TrimSpace(string(orig)), "\n") 216 217 cmd := exec.Command("cat", path) 218 cmd.SysProcAttr = &syscall.SysProcAttr{ 219 Unshareflags: syscall.CLONE_NEWNET, 220 } 221 out, err := cmd.CombinedOutput() 222 if err != nil { 223 if strings.Contains(err.Error(), "operation not permitted") { 224 // Issue 17206: despite all the checks above, 225 // this still reportedly fails for some users. 226 // (older kernels?). Just skip. 227 t.Skip("skipping due to permission error") 228 } 229 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 230 } 231 232 // Check there is only the local network interface 233 sout := strings.TrimSpace(string(out)) 234 if !strings.Contains(sout, "lo:") { 235 t.Fatalf("Expected lo network interface to exist, got %s", sout) 236 } 237 238 lines := strings.Split(sout, "\n") 239 if len(lines) >= len(origLines) { 240 t.Fatalf("Got %d lines of output, want <%d", len(lines), len(origLines)) 241 } 242 } 243 244 func TestGroupCleanup(t *testing.T) { 245 if os.Getuid() != 0 { 246 t.Skip("we need root for credential") 247 } 248 cmd := exec.Command("id") 249 cmd.SysProcAttr = &syscall.SysProcAttr{ 250 Credential: &syscall.Credential{ 251 Uid: 0, 252 Gid: 0, 253 }, 254 } 255 out, err := cmd.CombinedOutput() 256 if err != nil { 257 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 258 } 259 strOut := strings.TrimSpace(string(out)) 260 expected := "uid=0(root) gid=0(root)" 261 // Just check prefix because some distros reportedly output a 262 // context parameter; see https://golang.org/issue/16224. 263 // Alpine does not output groups; see https://golang.org/issue/19938. 264 if !strings.HasPrefix(strOut, expected) { 265 t.Errorf("id command output: %q, expected prefix: %q", strOut, expected) 266 } 267 } 268 269 func TestGroupCleanupUserNamespace(t *testing.T) { 270 if os.Getuid() != 0 { 271 t.Skip("we need root for credential") 272 } 273 checkUserNS(t) 274 cmd := exec.Command("id") 275 uid, gid := os.Getuid(), os.Getgid() 276 cmd.SysProcAttr = &syscall.SysProcAttr{ 277 Cloneflags: syscall.CLONE_NEWUSER, 278 Credential: &syscall.Credential{ 279 Uid: uint32(uid), 280 Gid: uint32(gid), 281 }, 282 UidMappings: []syscall.SysProcIDMap{ 283 {ContainerID: 0, HostID: uid, Size: 1}, 284 }, 285 GidMappings: []syscall.SysProcIDMap{ 286 {ContainerID: 0, HostID: gid, Size: 1}, 287 }, 288 } 289 out, err := cmd.CombinedOutput() 290 if err != nil { 291 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 292 } 293 strOut := strings.TrimSpace(string(out)) 294 295 // Strings we've seen in the wild. 296 expected := []string{ 297 "uid=0(root) gid=0(root) groups=0(root)", 298 "uid=0(root) gid=0(root) groups=0(root),65534(nobody)", 299 "uid=0(root) gid=0(root) groups=0(root),65534(nogroup)", 300 "uid=0(root) gid=0(root) groups=0(root),65534", 301 "uid=0(root) gid=0(root) groups=0(root),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody)", // Alpine; see https://golang.org/issue/19938 302 } 303 for _, e := range expected { 304 if strOut == e { 305 return 306 } 307 } 308 t.Errorf("id command output: %q, expected one of %q", strOut, expected) 309 } 310 311 // TestUnshareHelperProcess isn't a real test. It's used as a helper process 312 // for TestUnshareMountNameSpace. 313 func TestUnshareMountNameSpaceHelper(*testing.T) { 314 if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { 315 return 316 } 317 defer os.Exit(0) 318 if err := syscall.Mount("none", flag.Args()[0], "proc", 0, ""); err != nil { 319 fmt.Fprintf(os.Stderr, "unshare: mount %v failed: %v", os.Args, err) 320 os.Exit(2) 321 } 322 } 323 324 // Test for Issue 38471: unshare fails because systemd has forced / to be shared 325 func TestUnshareMountNameSpace(t *testing.T) { 326 skipInContainer(t) 327 // Make sure we are running as root so we have permissions to use unshare 328 // and create a network namespace. 329 if os.Getuid() != 0 { 330 t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace") 331 } 332 333 // When running under the Go continuous build, skip tests for 334 // now when under Kubernetes. (where things are root but not quite) 335 // Both of these are our own environment variables. 336 // See Issue 12815. 337 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 338 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 339 } 340 341 d, err := ioutil.TempDir("", "unshare") 342 if err != nil { 343 t.Fatalf("tempdir: %v", err) 344 } 345 346 cmd := exec.Command(os.Args[0], "-test.run=TestUnshareMountNameSpaceHelper", d) 347 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} 348 cmd.SysProcAttr = &syscall.SysProcAttr{Unshareflags: syscall.CLONE_NEWNS} 349 350 o, err := cmd.CombinedOutput() 351 if err != nil { 352 if strings.Contains(err.Error(), ": permission denied") { 353 t.Skipf("Skipping test (golang.org/issue/19698); unshare failed due to permissions: %s, %v", o, err) 354 } 355 t.Fatalf("unshare failed: %s, %v", o, err) 356 } 357 358 // How do we tell if the namespace was really unshared? It turns out 359 // to be simple: just try to remove the directory. If it's still mounted 360 // on the rm will fail with EBUSY. Then we have some cleanup to do: 361 // we must unmount it, then try to remove it again. 362 363 if err := os.Remove(d); err != nil { 364 t.Errorf("rmdir failed on %v: %v", d, err) 365 if err := syscall.Unmount(d, syscall.MNT_FORCE); err != nil { 366 t.Errorf("Can't unmount %v: %v", d, err) 367 } 368 if err := os.Remove(d); err != nil { 369 t.Errorf("rmdir after unmount failed on %v: %v", d, err) 370 } 371 } 372 } 373 374 // Test for Issue 20103: unshare fails when chroot is used 375 func TestUnshareMountNameSpaceChroot(t *testing.T) { 376 skipInContainer(t) 377 // Make sure we are running as root so we have permissions to use unshare 378 // and create a network namespace. 379 if os.Getuid() != 0 { 380 t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace") 381 } 382 383 // When running under the Go continuous build, skip tests for 384 // now when under Kubernetes. (where things are root but not quite) 385 // Both of these are our own environment variables. 386 // See Issue 12815. 387 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 388 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 389 } 390 391 d, err := ioutil.TempDir("", "unshare") 392 if err != nil { 393 t.Fatalf("tempdir: %v", err) 394 } 395 396 // Since we are doing a chroot, we need the binary there, 397 // and it must be statically linked. 398 x := filepath.Join(d, "syscall.test") 399 cmd := exec.Command(testenv.GoToolPath(t), "test", "-c", "-o", x, "syscall") 400 cmd.Env = append(os.Environ(), "CGO_ENABLED=0") 401 if o, err := cmd.CombinedOutput(); err != nil { 402 t.Fatalf("Build of syscall in chroot failed, output %v, err %v", o, err) 403 } 404 405 cmd = exec.Command("/syscall.test", "-test.run=TestUnshareMountNameSpaceHelper", "/") 406 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} 407 cmd.SysProcAttr = &syscall.SysProcAttr{Chroot: d, Unshareflags: syscall.CLONE_NEWNS} 408 409 o, err := cmd.CombinedOutput() 410 if err != nil { 411 if strings.Contains(err.Error(), ": permission denied") { 412 t.Skipf("Skipping test (golang.org/issue/19698); unshare failed due to permissions: %s, %v", o, err) 413 } 414 t.Fatalf("unshare failed: %s, %v", o, err) 415 } 416 417 // How do we tell if the namespace was really unshared? It turns out 418 // to be simple: just try to remove the executable. If it's still mounted 419 // on, the rm will fail. Then we have some cleanup to do: 420 // we must force unmount it, then try to remove it again. 421 422 if err := os.Remove(x); err != nil { 423 t.Errorf("rm failed on %v: %v", x, err) 424 if err := syscall.Unmount(d, syscall.MNT_FORCE); err != nil { 425 t.Fatalf("Can't unmount %v: %v", d, err) 426 } 427 if err := os.Remove(x); err != nil { 428 t.Fatalf("rm failed on %v: %v", x, err) 429 } 430 } 431 432 if err := os.Remove(d); err != nil { 433 t.Errorf("rmdir failed on %v: %v", d, err) 434 } 435 } 436 437 type capHeader struct { 438 version uint32 439 pid int 440 } 441 442 type capData struct { 443 effective uint32 444 permitted uint32 445 inheritable uint32 446 } 447 448 const CAP_SYS_TIME = 25 449 450 type caps struct { 451 hdr capHeader 452 data [2]capData 453 } 454 455 func getCaps() (caps, error) { 456 var c caps 457 458 // Get capability version 459 if _, _, errno := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(&c.hdr)), uintptr(unsafe.Pointer(nil)), 0); errno != 0 { 460 return c, fmt.Errorf("SYS_CAPGET: %v", errno) 461 } 462 463 // Get current capabilities 464 if _, _, errno := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(&c.hdr)), uintptr(unsafe.Pointer(&c.data[0])), 0); errno != 0 { 465 return c, fmt.Errorf("SYS_CAPGET: %v", errno) 466 } 467 468 return c, nil 469 } 470 471 func mustSupportAmbientCaps(t *testing.T) { 472 var uname syscall.Utsname 473 if err := syscall.Uname(&uname); err != nil { 474 t.Fatalf("Uname: %v", err) 475 } 476 var buf [65]byte 477 for i, b := range uname.Release { 478 buf[i] = byte(b) 479 } 480 ver := string(buf[:]) 481 if i := strings.Index(ver, "\x00"); i != -1 { 482 ver = ver[:i] 483 } 484 if strings.HasPrefix(ver, "2.") || 485 strings.HasPrefix(ver, "3.") || 486 strings.HasPrefix(ver, "4.1.") || 487 strings.HasPrefix(ver, "4.2.") { 488 t.Skipf("kernel version %q predates required 4.3; skipping test", ver) 489 } 490 } 491 492 // TestAmbientCapsHelper isn't a real test. It's used as a helper process for 493 // TestAmbientCaps. 494 func TestAmbientCapsHelper(*testing.T) { 495 if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { 496 return 497 } 498 defer os.Exit(0) 499 500 caps, err := getCaps() 501 if err != nil { 502 fmt.Fprintln(os.Stderr, err) 503 os.Exit(2) 504 } 505 if caps.data[0].effective&(1<<uint(CAP_SYS_TIME)) == 0 { 506 fmt.Fprintln(os.Stderr, "CAP_SYS_TIME unexpectedly not in the effective capability mask") 507 os.Exit(2) 508 } 509 } 510 511 func TestAmbientCaps(t *testing.T) { 512 skipInContainer(t) 513 // Make sure we are running as root so we have permissions to use unshare 514 // and create a network namespace. 515 if os.Getuid() != 0 { 516 t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace") 517 } 518 mustSupportAmbientCaps(t) 519 520 // When running under the Go continuous build, skip tests for 521 // now when under Kubernetes. (where things are root but not quite) 522 // Both of these are our own environment variables. 523 // See Issue 12815. 524 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 525 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 526 } 527 528 // skip on android, due to lack of lookup support 529 if runtime.GOOS == "android" { 530 t.Skip("skipping test on android; see Issue 27327") 531 } 532 533 caps, err := getCaps() 534 if err != nil { 535 t.Fatal(err) 536 } 537 538 // Add CAP_SYS_TIME to the permitted and inheritable capability mask, 539 // otherwise we will not be able to add it to the ambient capability mask. 540 caps.data[0].permitted |= 1 << uint(CAP_SYS_TIME) 541 caps.data[0].inheritable |= 1 << uint(CAP_SYS_TIME) 542 543 if _, _, errno := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(&caps.hdr)), uintptr(unsafe.Pointer(&caps.data[0])), 0); errno != 0 { 544 t.Fatalf("SYS_CAPSET: %v", errno) 545 } 546 547 u, err := user.Lookup("nobody") 548 if err != nil { 549 t.Fatal(err) 550 } 551 uid, err := strconv.ParseInt(u.Uid, 0, 32) 552 if err != nil { 553 t.Fatal(err) 554 } 555 gid, err := strconv.ParseInt(u.Gid, 0, 32) 556 if err != nil { 557 t.Fatal(err) 558 } 559 560 // Copy the test binary to a temporary location which is readable by nobody. 561 f, err := ioutil.TempFile("", "gotest") 562 if err != nil { 563 t.Fatal(err) 564 } 565 defer os.Remove(f.Name()) 566 defer f.Close() 567 e, err := os.Open(os.Args[0]) 568 if err != nil { 569 t.Fatal(err) 570 } 571 defer e.Close() 572 if _, err := io.Copy(f, e); err != nil { 573 t.Fatal(err) 574 } 575 if err := f.Chmod(0755); err != nil { 576 t.Fatal(err) 577 } 578 if err := f.Close(); err != nil { 579 t.Fatal(err) 580 } 581 582 cmd := exec.Command(f.Name(), "-test.run=TestAmbientCapsHelper") 583 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} 584 cmd.Stdout = os.Stdout 585 cmd.Stderr = os.Stderr 586 cmd.SysProcAttr = &syscall.SysProcAttr{ 587 Credential: &syscall.Credential{ 588 Uid: uint32(uid), 589 Gid: uint32(gid), 590 }, 591 AmbientCaps: []uintptr{CAP_SYS_TIME}, 592 } 593 if err := cmd.Run(); err != nil { 594 t.Fatal(err.Error()) 595 } 596 }