-
Notifications
You must be signed in to change notification settings - Fork 0
/
ambient.go
48 lines (43 loc) · 1.35 KB
/
ambient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// (c) Siemens AG 2023
//
// SPDX-License-Identifier: MIT
// How to pass capabilities to a child process (such as dumpcap) without having
// to give the binary file itself the capabilities...
package main
import (
"fmt"
caps "github.com/syndtr/gocapability/capability"
"golang.org/x/sys/unix"
)
// SetAmbient sets the specified ambient capabilities, at least if they are also
// currently effective.
func SetAmbient(ambcaps ...caps.Cap) error {
// Capabilities are per thread, not per process.
tid := unix.Gettid()
mycaps, err := caps.NewPid2(tid) // not sure, why deprecating NewPid() when it does the following anyway
if err == nil {
err = mycaps.Load()
}
if err != nil {
return fmt.Errorf("cannot query OS-thread capability sets: %s", err.Error())
}
// Next, prepare for setting the ambient capabilities from the specified
// set, but check against the currently effective capabilities.
ambs := []caps.Cap{}
for cap := caps.Cap(tid); cap <= caps.CAP_LAST_CAP; cap++ {
if mycaps.Get(caps.EFFECTIVE, cap) {
for _, c := range ambcaps {
if cap == c {
ambs = append(ambs, cap)
break
}
}
}
}
// Now actually set the ambient capabilities for the process.
mycaps.Set(caps.AMBIENT, ambs...)
if err := mycaps.Apply(caps.AMBIENT); err != nil {
return fmt.Errorf("cannot set ambient capabilities: %s", err.Error())
}
return nil
}