github.com/ActiveState/go@v0.0.0-20170614201249-0b81c023a722/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 "path/filepath" 16 "strings" 17 "syscall" 18 "testing" 19 ) 20 21 // Check if we are in a chroot by checking if the inode of / is 22 // different from 2 (there is no better test available to non-root on 23 // linux). 24 func isChrooted(t *testing.T) bool { 25 root, err := os.Stat("/") 26 if err != nil { 27 t.Fatalf("cannot stat /: %v", err) 28 } 29 return root.Sys().(*syscall.Stat_t).Ino != 2 30 } 31 32 func checkUserNS(t *testing.T) { 33 if _, err := os.Stat("/proc/self/ns/user"); err != nil { 34 if os.IsNotExist(err) { 35 t.Skip("kernel doesn't support user namespaces") 36 } 37 if os.IsPermission(err) { 38 t.Skip("unable to test user namespaces due to permissions") 39 } 40 t.Fatalf("Failed to stat /proc/self/ns/user: %v", err) 41 } 42 if isChrooted(t) { 43 // create_user_ns in the kernel (see 44 // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/kernel/user_namespace.c) 45 // forbids the creation of user namespaces when chrooted. 46 t.Skip("cannot create user namespaces when chrooted") 47 } 48 // On some systems, there is a sysctl setting. 49 if os.Getuid() != 0 { 50 data, errRead := ioutil.ReadFile("/proc/sys/kernel/unprivileged_userns_clone") 51 if errRead == nil && data[0] == '0' { 52 t.Skip("kernel prohibits user namespace in unprivileged process") 53 } 54 } 55 // When running under the Go continuous build, skip tests for 56 // now when under Kubernetes. (where things are root but not quite) 57 // Both of these are our own environment variables. 58 // See Issue 12815. 59 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 60 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 61 } 62 } 63 64 func whoamiCmd(t *testing.T, uid, gid int, setgroups bool) *exec.Cmd { 65 checkUserNS(t) 66 cmd := exec.Command("whoami") 67 cmd.SysProcAttr = &syscall.SysProcAttr{ 68 Cloneflags: syscall.CLONE_NEWUSER, 69 UidMappings: []syscall.SysProcIDMap{ 70 {ContainerID: 0, HostID: uid, Size: 1}, 71 }, 72 GidMappings: []syscall.SysProcIDMap{ 73 {ContainerID: 0, HostID: gid, Size: 1}, 74 }, 75 GidMappingsEnableSetgroups: setgroups, 76 } 77 return cmd 78 } 79 80 func testNEWUSERRemap(t *testing.T, uid, gid int, setgroups bool) { 81 cmd := whoamiCmd(t, uid, gid, setgroups) 82 out, err := cmd.CombinedOutput() 83 if err != nil { 84 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 85 } 86 sout := strings.TrimSpace(string(out)) 87 want := "root" 88 if sout != want { 89 t.Fatalf("whoami = %q; want %q", out, want) 90 } 91 } 92 93 func TestCloneNEWUSERAndRemapRootDisableSetgroups(t *testing.T) { 94 if os.Getuid() != 0 { 95 t.Skip("skipping root only test") 96 } 97 testNEWUSERRemap(t, 0, 0, false) 98 } 99 100 func TestCloneNEWUSERAndRemapRootEnableSetgroups(t *testing.T) { 101 if os.Getuid() != 0 { 102 t.Skip("skipping root only test") 103 } 104 testNEWUSERRemap(t, 0, 0, false) 105 } 106 107 func TestCloneNEWUSERAndRemapNoRootDisableSetgroups(t *testing.T) { 108 if os.Getuid() == 0 { 109 t.Skip("skipping unprivileged user only test") 110 } 111 testNEWUSERRemap(t, os.Getuid(), os.Getgid(), false) 112 } 113 114 func TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups(t *testing.T) { 115 if os.Getuid() == 0 { 116 t.Skip("skipping unprivileged user only test") 117 } 118 cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), true) 119 err := cmd.Run() 120 if err == nil { 121 t.Skip("probably old kernel without security fix") 122 } 123 if !os.IsPermission(err) { 124 t.Fatalf("Unprivileged gid_map rewriting with GidMappingsEnableSetgroups must fail") 125 } 126 } 127 128 func TestEmptyCredGroupsDisableSetgroups(t *testing.T) { 129 cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), false) 130 cmd.SysProcAttr.Credential = &syscall.Credential{} 131 if err := cmd.Run(); err != nil { 132 t.Fatal(err) 133 } 134 } 135 136 func TestUnshare(t *testing.T) { 137 // Make sure we are running as root so we have permissions to use unshare 138 // and create a network namespace. 139 if os.Getuid() != 0 { 140 t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace") 141 } 142 143 // When running under the Go continuous build, skip tests for 144 // now when under Kubernetes. (where things are root but not quite) 145 // Both of these are our own environment variables. 146 // See Issue 12815. 147 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 148 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 149 } 150 151 path := "/proc/net/dev" 152 if _, err := os.Stat(path); err != nil { 153 if os.IsNotExist(err) { 154 t.Skip("kernel doesn't support proc filesystem") 155 } 156 if os.IsPermission(err) { 157 t.Skip("unable to test proc filesystem due to permissions") 158 } 159 t.Fatal(err) 160 } 161 if _, err := os.Stat("/proc/self/ns/net"); err != nil { 162 if os.IsNotExist(err) { 163 t.Skip("kernel doesn't support net namespace") 164 } 165 t.Fatal(err) 166 } 167 168 orig, err := ioutil.ReadFile(path) 169 if err != nil { 170 t.Fatal(err) 171 } 172 origLines := strings.Split(strings.TrimSpace(string(orig)), "\n") 173 174 cmd := exec.Command("cat", path) 175 cmd.SysProcAttr = &syscall.SysProcAttr{ 176 Unshareflags: syscall.CLONE_NEWNET, 177 } 178 out, err := cmd.CombinedOutput() 179 if err != nil { 180 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 181 } 182 183 // Check there is only the local network interface 184 sout := strings.TrimSpace(string(out)) 185 if !strings.Contains(sout, "lo:") { 186 t.Fatalf("Expected lo network interface to exist, got %s", sout) 187 } 188 189 lines := strings.Split(sout, "\n") 190 if len(lines) >= len(origLines) { 191 t.Fatalf("Got %d lines of output, want <%d", len(lines), len(origLines)) 192 } 193 } 194 195 func TestGroupCleanup(t *testing.T) { 196 if os.Getuid() != 0 { 197 t.Skip("we need root for credential") 198 } 199 cmd := exec.Command("id") 200 cmd.SysProcAttr = &syscall.SysProcAttr{ 201 Credential: &syscall.Credential{ 202 Uid: 0, 203 Gid: 0, 204 }, 205 } 206 out, err := cmd.CombinedOutput() 207 if err != nil { 208 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 209 } 210 strOut := strings.TrimSpace(string(out)) 211 expected := "uid=0(root) gid=0(root)" 212 // Just check prefix because some distros reportedly output a 213 // context parameter; see https://golang.org/issue/16224. 214 // Alpine does not output groups; see https://golang.org/issue/19938. 215 if !strings.HasPrefix(strOut, expected) { 216 t.Errorf("id command output: %q, expected prefix: %q", strOut, expected) 217 } 218 } 219 220 func TestGroupCleanupUserNamespace(t *testing.T) { 221 if os.Getuid() != 0 { 222 t.Skip("we need root for credential") 223 } 224 checkUserNS(t) 225 cmd := exec.Command("id") 226 uid, gid := os.Getuid(), os.Getgid() 227 cmd.SysProcAttr = &syscall.SysProcAttr{ 228 Cloneflags: syscall.CLONE_NEWUSER, 229 Credential: &syscall.Credential{ 230 Uid: uint32(uid), 231 Gid: uint32(gid), 232 }, 233 UidMappings: []syscall.SysProcIDMap{ 234 {ContainerID: 0, HostID: uid, Size: 1}, 235 }, 236 GidMappings: []syscall.SysProcIDMap{ 237 {ContainerID: 0, HostID: gid, Size: 1}, 238 }, 239 } 240 out, err := cmd.CombinedOutput() 241 if err != nil { 242 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 243 } 244 strOut := strings.TrimSpace(string(out)) 245 246 // Strings we've seen in the wild. 247 expected := []string{ 248 "uid=0(root) gid=0(root) groups=0(root)", 249 "uid=0(root) gid=0(root) groups=0(root),65534(nobody)", 250 "uid=0(root) gid=0(root) groups=0(root),65534(nogroup)", 251 "uid=0(root) gid=0(root) groups=0(root),65534", 252 "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 253 } 254 for _, e := range expected { 255 if strOut == e { 256 return 257 } 258 } 259 t.Errorf("id command output: %q, expected one of %q", strOut, expected) 260 } 261 262 // TestUnshareHelperProcess isn't a real test. It's used as a helper process 263 // for TestUnshareMountNameSpace. 264 func TestUnshareMountNameSpaceHelper(*testing.T) { 265 if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { 266 return 267 } 268 defer os.Exit(0) 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 } 323 324 // Test for Issue 20103: unshare fails when chroot is used 325 func TestUnshareMountNameSpaceChroot(t *testing.T) { 326 // Make sure we are running as root so we have permissions to use unshare 327 // and create a network namespace. 328 if os.Getuid() != 0 { 329 t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace") 330 } 331 332 // When running under the Go continuous build, skip tests for 333 // now when under Kubernetes. (where things are root but not quite) 334 // Both of these are our own environment variables. 335 // See Issue 12815. 336 if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" { 337 t.Skip("skipping test on Kubernetes-based builders; see Issue 12815") 338 } 339 340 d, err := ioutil.TempDir("", "unshare") 341 if err != nil { 342 t.Fatalf("tempdir: %v", err) 343 } 344 345 // Since we are doing a chroot, we need the binary there, 346 // and it must be statically linked. 347 x := filepath.Join(d, "syscall.test") 348 cmd := exec.Command("go", "test", "-c", "-o", x, "syscall") 349 cmd.Env = append(os.Environ(), "CGO_ENABLED=0") 350 if o, err := cmd.CombinedOutput(); err != nil { 351 t.Fatalf("Build of syscall in chroot failed, output %v, err %v", o, err) 352 } 353 354 cmd = exec.Command("/syscall.test", "-test.run=TestUnshareMountNameSpaceHelper", "/") 355 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} 356 cmd.SysProcAttr = &syscall.SysProcAttr{Chroot: d, Unshareflags: syscall.CLONE_NEWNS} 357 358 o, err := cmd.CombinedOutput() 359 if err != nil { 360 if strings.Contains(err.Error(), ": permission denied") { 361 t.Skipf("Skipping test (golang.org/issue/19698); unshare failed due to permissions: %s, %v", o, err) 362 } 363 t.Fatalf("unshare failed: %s, %v", o, err) 364 } 365 366 // How do we tell if the namespace was really unshared? It turns out 367 // to be simple: just try to remove the executable. If it's still mounted 368 // on, the rm will fail. Then we have some cleanup to do: 369 // we must force unmount it, then try to remove it again. 370 371 if err := os.Remove(x); err != nil { 372 t.Errorf("rm failed on %v: %v", x, err) 373 if err := syscall.Unmount(d, syscall.MNT_FORCE); err != nil { 374 t.Fatalf("Can't unmount %v: %v", d, err) 375 } 376 if err := os.Remove(x); err != nil { 377 t.Fatalf("rm failed on %v: %v", x, err) 378 } 379 } 380 381 if err := os.Remove(d); err != nil { 382 t.Errorf("rmdir failed on %v: %v", d, err) 383 } 384 }