Black Lives Matter. Support the Equal Justice Initiative.

Source file src/syscall/exec_linux_test.go

Documentation: syscall

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

View as plain text