|
| 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 | + "os" |
| 11 | + "os/exec" |
| 12 | + "strings" |
| 13 | + "syscall" |
| 14 | + "testing" |
| 15 | +) |
| 16 | + |
| 17 | +func whoamiCmd(t *testing.T, uid int, setgroups bool) *exec.Cmd { |
| 18 | + if _, err := os.Stat("/proc/self/ns/user"); err != nil { |
| 19 | + if os.IsNotExist(err) { |
| 20 | + t.Skip("kernel doesn't support user namespaces") |
| 21 | + } |
| 22 | + t.Fatalf("Failed to stat /proc/self/ns/user: %v", err) |
| 23 | + } |
| 24 | + cmd := exec.Command("whoami") |
| 25 | + cmd.SysProcAttr = &syscall.SysProcAttr{ |
| 26 | + Cloneflags: syscall.CLONE_NEWUSER, |
| 27 | + UidMappings: []syscall.SysProcIDMap{ |
| 28 | + {ContainerID: 0, HostID: uid, Size: 1}, |
| 29 | + }, |
| 30 | + GidMappings: []syscall.SysProcIDMap{ |
| 31 | + {ContainerID: 0, HostID: uid, Size: 1}, |
| 32 | + }, |
| 33 | + GidMappingsEnableSetgroups: setgroups, |
| 34 | + } |
| 35 | + return cmd |
| 36 | +} |
| 37 | + |
| 38 | +func testNEWUSERRemap(t *testing.T, uid int, setgroups bool) { |
| 39 | + cmd := whoamiCmd(t, uid, setgroups) |
| 40 | + out, err := cmd.CombinedOutput() |
| 41 | + if err != nil { |
| 42 | + t.Fatalf("Cmd failed with err %v, output: %s", err, out) |
| 43 | + } |
| 44 | + sout := strings.TrimSpace(string(out)) |
| 45 | + want := "root" |
| 46 | + if sout != want { |
| 47 | + t.Fatalf("whoami = %q; want %q", out, want) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func TestCloneNEWUSERAndRemapRootDisableSetgroups(t *testing.T) { |
| 52 | + if os.Getuid() != 0 { |
| 53 | + t.Skip("skipping root only test") |
| 54 | + } |
| 55 | + testNEWUSERRemap(t, 0, false) |
| 56 | +} |
| 57 | + |
| 58 | +func TestCloneNEWUSERAndRemapRootEnableSetgroups(t *testing.T) { |
| 59 | + if os.Getuid() != 0 { |
| 60 | + t.Skip("skipping root only test") |
| 61 | + } |
| 62 | + testNEWUSERRemap(t, 0, false) |
| 63 | +} |
| 64 | + |
| 65 | +func TestCloneNEWUSERAndRemapNoRootDisableSetgroups(t *testing.T) { |
| 66 | + if os.Getuid() == 0 { |
| 67 | + t.Skip("skipping unprivileged user only test") |
| 68 | + } |
| 69 | + testNEWUSERRemap(t, os.Getuid(), false) |
| 70 | +} |
| 71 | + |
| 72 | +func TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups(t *testing.T) { |
| 73 | + if os.Getuid() == 0 { |
| 74 | + t.Skip("skipping unprivileged user only test") |
| 75 | + } |
| 76 | + cmd := whoamiCmd(t, os.Getuid(), true) |
| 77 | + err := cmd.Run() |
| 78 | + if err == nil { |
| 79 | + t.Skip("probably old kernel without security fix") |
| 80 | + } |
| 81 | + if !strings.Contains(err.Error(), "operation not permitted") { |
| 82 | + t.Fatalf("Unprivileged gid_map rewriting with GidMappingsEnableSetgroups must fail") |
| 83 | + } |
| 84 | +} |
0 commit comments