Debian Codegraph @

capability/capability_test.go

raw symbols SCIP
1 // Copyright 2023 The Capability 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 package capability_test
6
7 import (
8 "log"
9 "os"
10 "os/exec"
11 "runtime"
12 "strings"
13 "testing"
14
15 . "github.com/moby/sys/capability"
16 )
17
18 // Based on the fact Go 1.18+ supports Linux >= 2.6.32, and
19 // - CAP_MAC_ADMIN (33) was added in 2.6.25;
20 // - CAP_SYSLOG (34) was added in 2.6.38;
21 // - CAP_CHECKPOINT_RESTORE (40) was added in 5.9, and it is
22 // the last added capability as of today (July 2024);
23 //
24 // LastCap return value should be between minLastCap and maxLastCap.
25 const (
26 minLastCap = CAP_MAC_ADMIN
27 maxLastCap = CAP_CHECKPOINT_RESTORE
28 )
29
30 func requirePCapSet(t testing.TB) {
31 t.Helper()
32 pid, err := NewPid2(0)
33 if err != nil {
34 t.Fatal(err)
35 }
36 if err := pid.Load(); err != nil {
37 t.Fatal(err)
38 }
39 if !pid.Get(EFFECTIVE, CAP_SETPCAP) {
40 t.Skip("The test needs `CAP_SETPCAP`.")
41 }
42 }
43
44 // testInChild runs fn as a separate process, and returns its output.
45 // This is useful for tests which manipulate capabilities, allowing to
46 // preserve those of the main test process.
47 //
48 // The fn is a function which must end with os.Exit. In case exit code
49 // is non-zero, t.Fatal is called.
50 func testInChild(t *testing.T, fn func()) []byte {
51 if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
52 fn()
53 }
54
55 // Re-exec the current test as a new process.
56 args := []string{"-test.run=^" + t.Name() + "$"}
57 if testing.Verbose() {
58 args = append(args, "-test.v")
59 }
60 cmd := exec.Command("/proc/self/exe", args...)
61 cmd.Env = append(cmd.Environ(), "GO_WANT_HELPER_PROCESS=1")
62
63 out, err := cmd.CombinedOutput()
64 if err != nil {
65 t.Helper()
66 t.Fatalf("exec failed: %v\n\n%s\n", err, out)
67 }
68
69 return out
70 }
71
72 func TestLastCap(t *testing.T) {
73 last, err := LastCap()
74 switch runtime.GOOS {
75 default:
76 if err == nil {
77 t.Fatal(runtime.GOOS, ": want error, got nil")
78 }
79 return
80 case "linux":
81 }
82 if err != nil {
83 t.Fatalf("LastCap: want nil, got error: %v", err)
84 }
85 // Sanity checks.
86 if last < minLastCap {
87 t.Errorf("LastCap: want >= %d (%s), got %d (%s)",
88 last, last, minLastCap, minLastCap)
89 }
90 if last > maxLastCap {
91 t.Errorf("LastCap: want <= %d (%s), got %d (%s). Package needs to be updated.",
92 last, last, maxLastCap, maxLastCap)
93 }
94 }
95
96 func TestListSupported(t *testing.T) {
97 list, err := ListSupported()
98 switch runtime.GOOS {
99 default:
100 if err == nil {
101 t.Fatal(runtime.GOOS, ": want error, got nil")
102 }
103 return
104 case "linux":
105 }
106 if err != nil {
107 t.Fatalf("ListSupported: want nil, got error: %v", err)
108 }
109 t.Logf("got +%v (len %d)", list, len(list))
110 minLen := int(minLastCap) + 1
111 if len(list) < minLen {
112 t.Errorf("ListSupported: too short (want %d, got %d): +%v", minLen, len(list), list)
113 }
114 }
115
116 func TestNewPid2Load(t *testing.T) {
117 c, err := NewPid2(0)
118 switch runtime.GOOS {
119 default:
120 if err == nil {
121 t.Fatal(runtime.GOOS, ": want error, got nil")
122 }
123 return
124 case "linux":
125 }
126 if err != nil {
127 t.Fatalf("NewPid2: want nil, got error: %v", err)
128 }
129 err = c.Load()
130 if err != nil {
131 t.Fatalf("Load: %v", err)
132 }
133 // Assuming that at least bounding set is not empty.
134 bset := c.StringCap(BOUNDING)
135 t.Logf("Bounding set: %s", bset)
136 if len(bset) == 0 {
137 t.Fatal("loaded bounding set: want non-empty, got empty")
138 }
139 }
140
141 func TestAmbientCapSet(t *testing.T) {
142 if runtime.GOOS != "linux" {
143 return
144 }
145 requirePCapSet(t)
146
147 out := testInChild(t, childAmbientCapSet)
148
149 t.Logf("output from child:\n%s", out)
150 }
151
152 func childAmbientCapSet() {
153 runtime.LockOSThread()
154 // We can't use t.Log etc. here, yet filename and line number is nice
155 // to have. Set up and use the standard logger for this.
156 log.SetFlags(log.Lshortfile)
157
158 pid, err := NewPid2(0)
159 if err != nil {
160 log.Fatal(err)
161 }
162
163 list := []Cap{CAP_KILL, CAP_CHOWN, CAP_SYS_CHROOT}
164 pid.Set(CAPS|AMBIENT, list...)
165 if err = pid.Apply(CAPS | AMBIENT); err != nil {
166 log.Fatal(err)
167 }
168
169 // Check if ambient caps were applied.
170 if err = pid.Load(); err != nil {
171 log.Fatal(err)
172 }
173 for _, cap := range list {
174 want := true
175 if got := pid.Get(AMBIENT, cap); want != got {
176 log.Fatalf("Get(AMBIENT, %s): want %v, got %v", cap, want, got)
177 }
178 }
179
180 // Unset a single ambient cap, to check `PR_CAP_AMBIENT_CLEAR_ALL` work.
181 const unsetIdx = 1
182 pid.Unset(AMBIENT, list[unsetIdx])
183 if err = pid.Apply(AMBIENT); err != nil {
184 log.Fatal(err)
185 }
186
187 if err = pid.Load(); err != nil {
188 log.Fatal(err)
189 }
190 for i, cap := range list {
191 want := i != unsetIdx
192 if got := pid.Get(AMBIENT, cap); want != got {
193 log.Fatalf("Get(AMBIENT, %s): want %v, got %v", cap, want, got)
194 }
195 }
196 os.Exit(0)
197 }
198
199 // https://github.com/moby/sys/issues/168
200 func TestApplyOtherProcess(t *testing.T) {
201 if runtime.GOOS != "linux" {
202 return
203 }
204 requirePCapSet(t)
205
206 cmd := exec.Command("sleep", "infinity")
207 if err := cmd.Start(); err != nil {
208 t.Fatal(err)
209 }
210 t.Cleanup(func() {
211 _ = cmd.Process.Kill()
212 _, _ = cmd.Process.Wait()
213 })
214
215 pid, err := NewPid2(cmd.Process.Pid)
216 if err != nil {
217 t.Fatal(err)
218 }
219 pid.Clear(CAPS | BOUNDS | AMBS)
220
221 // See (*capsV3).Apply.
222 expErr := "unable to modify capabilities of another process"
223
224 for _, arg := range []CapType{CAPS, BOUNDS, AMBS} {
225 err = pid.Apply(arg)
226 if !strings.Contains(err.Error(), expErr) {
227 t.Errorf("Apply(%q): want error to contain %q; got %v", arg, expErr, err)
228 }
229 }
230 }
231
232 func TestGetSetResetAmbient(t *testing.T) {
233 if runtime.GOOS != "linux" {
234 _, err := GetAmbient(Cap(0))
235 if err == nil {
236 t.Error(runtime.GOOS, ": want error, got nil")
237 }
238 err = SetAmbient(false, Cap(0))
239 if err == nil {
240 t.Error(runtime.GOOS, ": want error, got nil")
241 }
242 err = ResetAmbient()
243 if err == nil {
244 t.Error(runtime.GOOS, ": want error, got nil")
245 }
246 return
247 }
248
249 requirePCapSet(t)
250 out := testInChild(t, childGetSetResetAmbient)
251 t.Logf("output from child:\n%s", out)
252 }
253
254 func childGetSetResetAmbient() {
255 runtime.LockOSThread()
256 log.SetFlags(log.Lshortfile)
257
258 pid, err := NewPid2(0)
259 if err != nil {
260 log.Fatal(err)
261 }
262
263 list := []Cap{CAP_KILL, CAP_CHOWN, CAP_SYS_CHROOT}
264 pid.Set(CAPS, list...)
265 if err = pid.Apply(CAPS); err != nil {
266 log.Fatal(err)
267 }
268
269 // Set ambient caps from list.
270 if err = SetAmbient(true, list...); err != nil {
271 log.Fatal(err)
272 }
273
274 // Check if they were set as expected.
275 for _, cap := range list {
276 want := true
277 got, err := GetAmbient(cap)
278 if err != nil {
279 log.Fatalf("GetAmbient(%s): want nil, got error %v", cap, err)
280 } else if want != got {
281 log.Fatalf("Get(AMBIENT, %s): want %v, got %v", cap, want, got)
282 }
283 }
284
285 // Lower one ambient cap.
286 const unsetIdx = 1
287 if err = SetAmbient(false, list[unsetIdx]); err != nil {
288 log.Fatal(err)
289 }
290 // Check they are set as expected.
291 for i, cap := range list {
292 want := i != unsetIdx
293 got, err := GetAmbient(cap)
294 if err != nil {
295 log.Fatalf("GetAmbient(%s): want nil, got error %v", cap, err)
296 } else if want != got {
297 log.Fatalf("Get(AMBIENT, %s): want %v, got %v", cap, want, got)
298 }
299 }
300
301 // Lower all ambient caps.
302 if err = ResetAmbient(); err != nil {
303 log.Fatal(err)
304 }
305 for _, cap := range list {
306 want := false
307 got, err := GetAmbient(cap)
308 if err != nil {
309 log.Fatalf("GetAmbient(%s): want nil, got error %v", cap, err)
310 } else if want != got {
311 log.Fatalf("Get(AMBIENT, %s): want %v, got %v", cap, want, got)
312 }
313 }
314 os.Exit(0)
315 }
316
317 func TestGetBound(t *testing.T) {
318 if runtime.GOOS != "linux" {
319 _, err := GetBound(Cap(0))
320 if err == nil {
321 t.Error(runtime.GOOS, ": want error, got nil")
322 }
323 return
324 }
325
326 last, err := LastCap()
327 if err != nil {
328 t.Fatalf("LastCap: %v", err)
329 }
330 for i := Cap(0); i < Cap(63); i++ {
331 wantErr := i > last
332 set, err := GetBound(i)
333 t.Logf("GetBound(%q): %v, %v", i, set, err)
334 if wantErr && err == nil {
335 t.Errorf("GetBound(%q): want err, got nil", i)
336 } else if !wantErr && err != nil {
337 t.Errorf("GetBound(%q): want nil, got error %v", i, err)
338 }
339 }
340 }
341
342 func TestDropBound(t *testing.T) {
343 if runtime.GOOS != "linux" {
344 err := DropBound(Cap(0))
345 if err == nil {
346 t.Error(runtime.GOOS, ": want error, got nil")
347 }
348 return
349 }
350
351 requirePCapSet(t)
352 out := testInChild(t, childDropBound)
353 t.Logf("output from child:\n%s", out)
354 }
355
356 func childDropBound() {
357 runtime.LockOSThread()
358 log.SetFlags(log.Lshortfile)
359
360 for i := Cap(2); i < Cap(4); i++ {
361 err := DropBound(i)
362 if err != nil {
363 log.Fatalf("DropBound(%q): want nil, got error %v", i, err)
364 }
365 set, err := GetBound(i)
366 if err != nil {
367 log.Fatalf("GetBound(%q): want nil, got error %v", i, err)
368 }
369 if set {
370 log.Fatalf("GetBound(%q): want false, got true", i)
371 }
372 }
373
374 os.Exit(0)
375 }