github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/src/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  	"io/ioutil"
    13  	"os"
    14  	"os/exec"
    15  	"strings"
    16  	"syscall"
    17  	"testing"
    18  )
    19  
    20  // Check if we are in a chroot by checking if the inode of / is
    21  // different from 2 (there is no better test available to non-root on
    22  // linux).
    23  func isChrooted(t *testing.T) bool {
    24  	root, err := os.Stat("/")
    25  	if err != nil {
    26  		t.Fatalf("cannot stat /: %v", err)
    27  	}
    28  	return root.Sys().(*syscall.Stat_t).Ino != 2
    29  }
    30  
    31  func checkUserNS(t *testing.T) {
    32  	if _, err := os.Stat("/proc/self/ns/user"); err != nil {
    33  		if os.IsNotExist(err) {
    34  			t.Skip("kernel doesn't support user namespaces")
    35  		}
    36  		if os.IsPermission(err) {
    37  			t.Skip("unable to test user namespaces due to permissions")
    38  		}
    39  		t.Fatalf("Failed to stat /proc/self/ns/user: %v", err)
    40  	}
    41  	if isChrooted(t) {
    42  		// create_user_ns in the kernel (see
    43  		// https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/kernel/user_namespace.c)
    44  		// forbids the creation of user namespaces when chrooted.
    45  		t.Skip("cannot create user namespaces when chrooted")
    46  	}
    47  	// On some systems, there is a sysctl setting.
    48  	if os.Getuid() != 0 {
    49  		data, errRead := ioutil.ReadFile("/proc/sys/kernel/unprivileged_userns_clone")
    50  		if errRead == nil && data[0] == '0' {
    51  			t.Skip("kernel prohibits user namespace in unprivileged process")
    52  		}
    53  	}
    54  	// When running under the Go continuous build, skip tests for
    55  	// now when under Kubernetes. (where things are root but not quite)
    56  	// Both of these are our own environment variables.
    57  	// See Issue 12815.
    58  	if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" {
    59  		t.Skip("skipping test on Kubernetes-based builders; see Issue 12815")
    60  	}
    61  }
    62  
    63  func whoamiCmd(t *testing.T, uid, gid int, setgroups bool) *exec.Cmd {
    64  	checkUserNS(t)
    65  	cmd := exec.Command("whoami")
    66  	cmd.SysProcAttr = &syscall.SysProcAttr{
    67  		Cloneflags: syscall.CLONE_NEWUSER,
    68  		UidMappings: []syscall.SysProcIDMap{
    69  			{ContainerID: 0, HostID: uid, Size: 1},
    70  		},
    71  		GidMappings: []syscall.SysProcIDMap{
    72  			{ContainerID: 0, HostID: gid, Size: 1},
    73  		},
    74  		GidMappingsEnableSetgroups: setgroups,
    75  	}
    76  	return cmd
    77  }
    78  
    79  func testNEWUSERRemap(t *testing.T, uid, gid int, setgroups bool) {
    80  	cmd := whoamiCmd(t, uid, gid, setgroups)
    81  	out, err := cmd.CombinedOutput()
    82  	if err != nil {
    83  		t.Fatalf("Cmd failed with err %v, output: %s", err, out)
    84  	}
    85  	sout := strings.TrimSpace(string(out))
    86  	want := "root"
    87  	if sout != want {
    88  		t.Fatalf("whoami = %q; want %q", out, want)
    89  	}
    90  }
    91  
    92  func TestCloneNEWUSERAndRemapRootDisableSetgroups(t *testing.T) {
    93  	if os.Getuid() != 0 {
    94  		t.Skip("skipping root only test")
    95  	}
    96  	testNEWUSERRemap(t, 0, 0, false)
    97  }
    98  
    99  func TestCloneNEWUSERAndRemapRootEnableSetgroups(t *testing.T) {
   100  	if os.Getuid() != 0 {
   101  		t.Skip("skipping root only test")
   102  	}
   103  	testNEWUSERRemap(t, 0, 0, false)
   104  }
   105  
   106  func TestCloneNEWUSERAndRemapNoRootDisableSetgroups(t *testing.T) {
   107  	if os.Getuid() == 0 {
   108  		t.Skip("skipping unprivileged user only test")
   109  	}
   110  	testNEWUSERRemap(t, os.Getuid(), os.Getgid(), false)
   111  }
   112  
   113  func TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups(t *testing.T) {
   114  	if os.Getuid() == 0 {
   115  		t.Skip("skipping unprivileged user only test")
   116  	}
   117  	cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), true)
   118  	err := cmd.Run()
   119  	if err == nil {
   120  		t.Skip("probably old kernel without security fix")
   121  	}
   122  	if !os.IsPermission(err) {
   123  		t.Fatalf("Unprivileged gid_map rewriting with GidMappingsEnableSetgroups must fail")
   124  	}
   125  }
   126  
   127  func TestEmptyCredGroupsDisableSetgroups(t *testing.T) {
   128  	cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), false)
   129  	cmd.SysProcAttr.Credential = &syscall.Credential{}
   130  	if err := cmd.Run(); err != nil {
   131  		t.Fatal(err)
   132  	}
   133  }
   134  
   135  func TestUnshare(t *testing.T) {
   136  	// Make sure we are running as root so we have permissions to use unshare
   137  	// and create a network namespace.
   138  	if os.Getuid() != 0 {
   139  		t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace")
   140  	}
   141  
   142  	// When running under the Go continuous build, skip tests for
   143  	// now when under Kubernetes. (where things are root but not quite)
   144  	// Both of these are our own environment variables.
   145  	// See Issue 12815.
   146  	if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" {
   147  		t.Skip("skipping test on Kubernetes-based builders; see Issue 12815")
   148  	}
   149  
   150  	path := "/proc/net/dev"
   151  	if _, err := os.Stat(path); err != nil {
   152  		if os.IsNotExist(err) {
   153  			t.Skip("kernel doesn't support proc filesystem")
   154  		}
   155  		if os.IsPermission(err) {
   156  			t.Skip("unable to test proc filesystem due to permissions")
   157  		}
   158  		t.Fatal(err)
   159  	}
   160  	if _, err := os.Stat("/proc/self/ns/net"); err != nil {
   161  		if os.IsNotExist(err) {
   162  			t.Skip("kernel doesn't support net namespace")
   163  		}
   164  		t.Fatal(err)
   165  	}
   166  
   167  	orig, err := ioutil.ReadFile(path)
   168  	if err != nil {
   169  		t.Fatal(err)
   170  	}
   171  	origLines := strings.Split(strings.TrimSpace(string(orig)), "\n")
   172  
   173  	cmd := exec.Command("cat", path)
   174  	cmd.SysProcAttr = &syscall.SysProcAttr{
   175  		Unshareflags: syscall.CLONE_NEWNET,
   176  	}
   177  	out, err := cmd.CombinedOutput()
   178  	if err != nil {
   179  		t.Fatalf("Cmd failed with err %v, output: %s", err, out)
   180  	}
   181  
   182  	// Check there is only the local network interface
   183  	sout := strings.TrimSpace(string(out))
   184  	if !strings.Contains(sout, "lo:") {
   185  		t.Fatalf("Expected lo network interface to exist, got %s", sout)
   186  	}
   187  
   188  	lines := strings.Split(sout, "\n")
   189  	if len(lines) >= len(origLines) {
   190  		t.Fatalf("Got %d lines of output, want <%d", len(lines), len(origLines))
   191  	}
   192  }
   193  
   194  func TestGroupCleanup(t *testing.T) {
   195  	if os.Getuid() != 0 {
   196  		t.Skip("we need root for credential")
   197  	}
   198  	cmd := exec.Command("id")
   199  	cmd.SysProcAttr = &syscall.SysProcAttr{
   200  		Credential: &syscall.Credential{
   201  			Uid: 0,
   202  			Gid: 0,
   203  		},
   204  	}
   205  	out, err := cmd.CombinedOutput()
   206  	if err != nil {
   207  		t.Fatalf("Cmd failed with err %v, output: %s", err, out)
   208  	}
   209  	strOut := strings.TrimSpace(string(out))
   210  	expected := "uid=0(root) gid=0(root)"
   211  	// Just check prefix because some distros reportedly output a
   212  	// context parameter; see https://golang.org/issue/16224.
   213  	// Alpine does not output groups; see https://golang.org/issue/19938.
   214  	if !strings.HasPrefix(strOut, expected) {
   215  		t.Errorf("id command output: %q, expected prefix: %q", strOut, expected)
   216  	}
   217  }
   218  
   219  func TestGroupCleanupUserNamespace(t *testing.T) {
   220  	if os.Getuid() != 0 {
   221  		t.Skip("we need root for credential")
   222  	}
   223  	checkUserNS(t)
   224  	cmd := exec.Command("id")
   225  	uid, gid := os.Getuid(), os.Getgid()
   226  	cmd.SysProcAttr = &syscall.SysProcAttr{
   227  		Cloneflags: syscall.CLONE_NEWUSER,
   228  		Credential: &syscall.Credential{
   229  			Uid: uint32(uid),
   230  			Gid: uint32(gid),
   231  		},
   232  		UidMappings: []syscall.SysProcIDMap{
   233  			{ContainerID: 0, HostID: uid, Size: 1},
   234  		},
   235  		GidMappings: []syscall.SysProcIDMap{
   236  			{ContainerID: 0, HostID: gid, Size: 1},
   237  		},
   238  	}
   239  	out, err := cmd.CombinedOutput()
   240  	if err != nil {
   241  		t.Fatalf("Cmd failed with err %v, output: %s", err, out)
   242  	}
   243  	strOut := strings.TrimSpace(string(out))
   244  
   245  	// Strings we've seen in the wild.
   246  	expected := []string{
   247  		"uid=0(root) gid=0(root) groups=0(root)",
   248  		"uid=0(root) gid=0(root) groups=0(root),65534(nobody)",
   249  		"uid=0(root) gid=0(root) groups=0(root),65534(nogroup)",
   250  		"uid=0(root) gid=0(root) groups=0(root),65534",
   251  		"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
   252  	}
   253  	for _, e := range expected {
   254  		if strOut == e {
   255  			return
   256  		}
   257  	}
   258  	t.Errorf("id command output: %q, expected one of %q", strOut, expected)
   259  }
   260  
   261  // TestUnshareHelperProcess isn't a real test. It's used as a helper process
   262  // for TestUnshareMountNameSpace.
   263  func TestUnshareMountNameSpaceHelper(*testing.T) {
   264  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
   265  		return
   266  	}
   267  	defer os.Exit(0)
   268  
   269  	if err := syscall.Mount("none", flag.Args()[0], "proc", 0, ""); err != nil {
   270  		fmt.Fprintf(os.Stderr, "unshare: mount %v failed: %v", os.Args, err)
   271  		os.Exit(2)
   272  	}
   273  }
   274  
   275  // Test for Issue 38471: unshare fails because systemd has forced / to be shared
   276  func TestUnshareMountNameSpace(t *testing.T) {
   277  	// Make sure we are running as root so we have permissions to use unshare
   278  	// and create a network namespace.
   279  	if os.Getuid() != 0 {
   280  		t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace")
   281  	}
   282  
   283  	// When running under the Go continuous build, skip tests for
   284  	// now when under Kubernetes. (where things are root but not quite)
   285  	// Both of these are our own environment variables.
   286  	// See Issue 12815.
   287  	if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" {
   288  		t.Skip("skipping test on Kubernetes-based builders; see Issue 12815")
   289  	}
   290  
   291  	d, err := ioutil.TempDir("", "unshare")
   292  	if err != nil {
   293  		t.Fatalf("tempdir: %v", err)
   294  	}
   295  
   296  	cmd := exec.Command(os.Args[0], "-test.run=TestUnshareMountNameSpaceHelper", d)
   297  	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
   298  	cmd.SysProcAttr = &syscall.SysProcAttr{Unshareflags: syscall.CLONE_NEWNS}
   299  
   300  	o, err := cmd.CombinedOutput()
   301  	if err != nil {
   302  		if strings.Contains(err.Error(), ": permission denied") {
   303  			t.Skipf("Skipping test (golang.org/issue/19698); unshare failed due to permissions: %s, %v", o, err)
   304  		}
   305  		t.Fatalf("unshare failed: %s, %v", o, err)
   306  	}
   307  
   308  	// How do we tell if the namespace was really unshared? It turns out
   309  	// to be simple: just try to remove the directory. If it's still mounted
   310  	// on the rm will fail with EBUSY. Then we have some cleanup to do:
   311  	// we must unmount it, then try to remove it again.
   312  
   313  	if err := os.Remove(d); err != nil {
   314  		t.Errorf("rmdir failed on %v: %v", d, err)
   315  		if err := syscall.Unmount(d, syscall.MNT_FORCE); err != nil {
   316  			t.Errorf("Can't unmount %v: %v", d, err)
   317  		}
   318  		if err := os.Remove(d); err != nil {
   319  			t.Errorf("rmdir after unmount failed on %v: %v", d, err)
   320  		}
   321  	}
   322  }