github.com/jonasi/go@v0.0.0-20150930005915-e78e654c1de0/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 "io/ioutil" 11 "os" 12 "os/exec" 13 "strings" 14 "syscall" 15 "testing" 16 ) 17 18 func whoamiCmd(t *testing.T, uid, gid int, setgroups bool) *exec.Cmd { 19 if _, err := os.Stat("/proc/self/ns/user"); err != nil { 20 if os.IsNotExist(err) { 21 t.Skip("kernel doesn't support user namespaces") 22 } 23 t.Fatalf("Failed to stat /proc/self/ns/user: %v", err) 24 } 25 // On some systems, there is a sysctl setting. 26 if os.Getuid() != 0 { 27 data, errRead := ioutil.ReadFile("/proc/sys/kernel/unprivileged_userns_clone") 28 if errRead == nil && data[0] == '0' { 29 t.Skip("kernel prohibits user namespace in unprivileged process") 30 } 31 } 32 cmd := exec.Command("whoami") 33 cmd.SysProcAttr = &syscall.SysProcAttr{ 34 Cloneflags: syscall.CLONE_NEWUSER, 35 UidMappings: []syscall.SysProcIDMap{ 36 {ContainerID: 0, HostID: uid, Size: 1}, 37 }, 38 GidMappings: []syscall.SysProcIDMap{ 39 {ContainerID: 0, HostID: gid, Size: 1}, 40 }, 41 GidMappingsEnableSetgroups: setgroups, 42 } 43 return cmd 44 } 45 46 func testNEWUSERRemap(t *testing.T, uid, gid int, setgroups bool) { 47 cmd := whoamiCmd(t, uid, gid, setgroups) 48 out, err := cmd.CombinedOutput() 49 if err != nil { 50 t.Fatalf("Cmd failed with err %v, output: %s", err, out) 51 } 52 sout := strings.TrimSpace(string(out)) 53 want := "root" 54 if sout != want { 55 t.Fatalf("whoami = %q; want %q", out, want) 56 } 57 } 58 59 func TestCloneNEWUSERAndRemapRootDisableSetgroups(t *testing.T) { 60 if os.Getuid() != 0 { 61 t.Skip("skipping root only test") 62 } 63 testNEWUSERRemap(t, 0, 0, false) 64 } 65 66 func TestCloneNEWUSERAndRemapRootEnableSetgroups(t *testing.T) { 67 if os.Getuid() != 0 { 68 t.Skip("skipping root only test") 69 } 70 testNEWUSERRemap(t, 0, 0, false) 71 } 72 73 func TestCloneNEWUSERAndRemapNoRootDisableSetgroups(t *testing.T) { 74 if os.Getuid() == 0 { 75 t.Skip("skipping unprivileged user only test") 76 } 77 testNEWUSERRemap(t, os.Getuid(), os.Getgid(), false) 78 } 79 80 func TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups(t *testing.T) { 81 if os.Getuid() == 0 { 82 t.Skip("skipping unprivileged user only test") 83 } 84 cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), true) 85 err := cmd.Run() 86 if err == nil { 87 t.Skip("probably old kernel without security fix") 88 } 89 if !os.IsPermission(err) { 90 t.Fatalf("Unprivileged gid_map rewriting with GidMappingsEnableSetgroups must fail") 91 } 92 } 93 94 func TestEmptyCredGroupsDisableSetgroups(t *testing.T) { 95 cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), false) 96 cmd.SysProcAttr.Credential = &syscall.Credential{} 97 if err := cmd.Run(); err != nil { 98 t.Fatal(err) 99 } 100 }