Debian Codegraph @

cap/cap.go

raw
1 // Package cap provides all the Linux Capabilities userspace library API
2 // bindings in native Go.
3 //
4 // Capabilities are a feature of the Linux kernel that allow fine
5 // grain permissions to perform privileged operations. Privileged
6 // operations are required to do irregular system level operations
7 // from code. You can read more about how Capabilities are intended to
8 // work in this [Linux Symposium paper].
9 //
10 // This package supports native Go bindings for all the features
11 // described in that paper as well as supporting subsequent changes to
12 // the kernel for other styles of inheritable Capability.
13 //
14 // Some simple things you can do with this package are:
15 //
16 // // Read and display the capabilities of the running process
17 // c := cap.GetProc()
18 // iab := cap.IABGetProc()
19 // log.Printf("this process has these caps: %q [%v]", c, iab)
20 //
21 // // Drop any privilege a process might have (including for root,
22 // // but note root 'owns' a lot of system files so a cap-limited
23 // // root can still do considerable damage to a running system).
24 // old := cap.GetProc()
25 // empty := cap.NewSet()
26 // if err := empty.SetProc(); err != nil {
27 // log.Fatalf("failed to drop privilege: %q -> %q: %v", old, empty, err)
28 // }
29 // now := cap.GetProc()
30 // if cf, _ := now.Cf(empty); cf != 0 {
31 // log.Fatalf("failed to fully drop privilege: have=%q, wanted=%q", now, empty)
32 // }
33 //
34 // This `"cap"` package operates with POSIX semantics for security
35 // state. That is all OS threads are kept in sync at all times. The
36 // package `"kernel.org/pub/linux/libs/security/libcap/psx"` is used
37 // to implement POSIX semantics system calls that manipulate thread
38 // state uniformly over the whole Go (and any CGo linked) process
39 // runtime.
40 //
41 // Note, if the Go runtime syscall interface contains the Linux
42 // variant `syscall.AllThreadsSyscall()` API (it debuted in go1.16 see
43 // [Go bug 1435] for its history) then the "libcap/psx" package will
44 // use that to invoke Capability setting system calls in pure Go
45 // binaries. With such an enhanced Go runtime, to force this behavior,
46 // use the CGO_ENABLED=0 environment variable.
47 //
48 // POSIX semantics are more secure than trying to manage privilege at
49 // a thread level when those threads share a common memory image as
50 // they do under Linux: it is trivial to exploit a vulnerability in
51 // one thread of a process to cause execution on any another
52 // thread. So, any imbalance in security state, in such cases will
53 // readily create an opportunity for a privilege escalation
54 // vulnerability.
55 //
56 // POSIX semantics also work well with Go, which deliberately tries to
57 // insulate the user from worrying about the number of OS threads that
58 // are actually running in their program. Indeed, Go can efficiently
59 // launch and manage tens of thousands of concurrent goroutines
60 // without bogging the program or wider system down. It does this by
61 // aggressively migrating idle threads to make progress on unblocked
62 // goroutines. So, inconsistent security state across OS threads can
63 // also lead to program misbehavior.
64 //
65 // The only exception to this process-wide common security state is
66 // the cap.Launcher related functionality. This briefly locks an OS
67 // thread to a goroutine in order to launch another executable - the
68 // robust implementation of this kind of support is quite subtle, so
69 // please read its documentation carefully, if you find that you need
70 // it.
71 //
72 // See [the Fully Capable site] for recent updates,
73 // some more complete walk-through examples of ways of using
74 // 'cap.Set's etc and information on how to file bugs.
75 //
76 // Copyright (c) 2019-21 Andrew G. Morgan <[email protected]>
77 //
78 // The cap and psx packages are licensed with a (you choose) BSD
79 // 3-clause or GPL2. See LICENSE file for details.
80 //
81 // [Linux Symposium paper]: https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/33528.pdf
82 // [Go bug 1435]: https://github.com/golang/go/issues/1435
83 // [the Fully Capable site]: https://sites.google.com/site/fullycapable/
84 package cap // import "kernel.org/pub/linux/libs/security/libcap/cap"
85
86 import (
87 "errors"
88 "sort"
89 "sync"
90 "syscall"
91 "unsafe"
92 )
93
94 // Value is the type of a single capability (or permission) bit.
95 type Value uint
96
97 // Flag is the type of one of the three Value dimensions held in a
98 // Set. It is also used in the (*IAB).Fill() method for changing the
99 // Bounding and Ambient Vectors.
100 type Flag uint
101
102 // Effective, Permitted, Inheritable are the three Flags of Values
103 // held in a Set.
104 const (
105 Effective Flag = iota
106 Permitted
107 Inheritable
108 )
109
110 // Diff summarizes the result of the (*Set).Cf() function.
111 type Diff uint
112
113 const (
114 effectiveDiff Diff = 1 << Effective
115 permittedDiff Diff = 1 << Permitted
116 inheritableDiff Diff = 1 << Inheritable
117 )
118
119 // String identifies a Flag value by its conventional "e", "p" or "i"
120 // string abbreviation.
121 func (f Flag) String() string {
122 switch f {
123 case Effective:
124 return "e"
125 case Permitted:
126 return "p"
127 case Inheritable:
128 return "i"
129 default:
130 return "<Error>"
131 }
132 }
133
134 // data holds a 32-bit slice of the compressed bitmaps of capability
135 // sets as understood by the kernel.
136 type data [Inheritable + 1]uint32
137
138 // Set is an opaque capabilities container for a set of system
139 // capbilities. It holds individually addressable capability Value's
140 // for the three capability Flag's. See GetFlag() and SetFlag() for
141 // how to adjust them individually, and Clear() and ClearFlag() for
142 // how to do bulk operations.
143 //
144 // For admin tasks associated with managing namespace specific file
145 // capabilities, Set can also support a namespace-root-UID value which
146 // defaults to zero. See GetNSOwner() and SetNSOwner().
147 type Set struct {
148 // mu protects all other members of a Set.
149 mu sync.RWMutex
150
151 // flat holds Flag Value bitmaps for all capabilities
152 // associated with this Set.
153 flat []data
154
155 // Linux specific
156 nsRoot int
157 }
158
159 // Various known kernel magic values.
160 const (
161 kv1 = 0x19980330 // First iteration of process capabilities (32 bits).
162 kv2 = 0x20071026 // First iteration of process and file capabilities (64 bits) - deprecated.
163 kv3 = 0x20080522 // Most recently supported process and file capabilities (64 bits).
164 )
165
166 var (
167 // startUp protects setting of the following values: magic,
168 // words, maxValues.
169 startUp sync.Once
170
171 // magic holds the preferred magic number for the kernel ABI.
172 magic uint32
173
174 // words holds the number of uint32's associated with each
175 // capability Flag for this session.
176 words int
177
178 // maxValues holds the number of bit values that are named by
179 // the running kernel. This is generally expected to match
180 // ValueCount which is autogenerated at packaging time.
181 maxValues uint
182 )
183
184 type header struct {
185 magic uint32
186 pid int32
187 }
188
189 // syscaller is a type for abstracting syscalls. The r* variants are
190 // for reading state, and can be parallelized, the w* variants need to
191 // be serialized so all OS threads can share state.
192 type syscaller struct {
193 r3 func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
194 w3 func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
195 r6 func(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
196 w6 func(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
197 }
198
199 // caprcall provides a pointer etc wrapper for the system calls
200 // associated with getcap.
201 //
202 //go:uintptrescapes
203 func (sc *syscaller) caprcall(call uintptr, h *header, d []data) error {
204 x := uintptr(0)
205 if d != nil {
206 x = uintptr(unsafe.Pointer(&d[0]))
207 }
208 _, _, err := sc.r3(call, uintptr(unsafe.Pointer(h)), x, 0)
209 if err != 0 {
210 return err
211 }
212 return nil
213 }
214
215 // capwcall provides a pointer etc wrapper for the system calls
216 // associated with setcap.
217 //
218 //go:uintptrescapes
219 func (sc *syscaller) capwcall(call uintptr, h *header, d []data) error {
220 x := uintptr(0)
221 if d != nil {
222 x = uintptr(unsafe.Pointer(&d[0]))
223 }
224 _, _, err := sc.w3(call, uintptr(unsafe.Pointer(h)), x, 0)
225 if err != 0 {
226 return err
227 }
228 return nil
229 }
230
231 // prctlrcall provides a wrapper for the prctl systemcalls that only
232 // read kernel state. There is a limited number of arguments needed
233 // and the caller should use 0 for those not needed.
234 func (sc *syscaller) prctlrcall(prVal, v1, v2 uintptr) (int, error) {
235 r, _, err := sc.r3(syscall.SYS_PRCTL, prVal, v1, v2)
236 if err != 0 {
237 return int(r), err
238 }
239 return int(r), nil
240 }
241
242 // prctlrcall6 provides a wrapper for the prctl systemcalls that only
243 // read kernel state and require 6 arguments - ambient cap API, I'm
244 // looking at you. There is a limited number of arguments needed and
245 // the caller should use 0 for those not needed.
246 func (sc *syscaller) prctlrcall6(prVal, v1, v2, v3, v4, v5 uintptr) (int, error) {
247 r, _, err := sc.r6(syscall.SYS_PRCTL, prVal, v1, v2, v3, v4, v5)
248 if err != 0 {
249 return int(r), err
250 }
251 return int(r), nil
252 }
253
254 // prctlwcall provides a wrapper for the prctl systemcalls that
255 // write/modify kernel state. Where available, these will use the
256 // POSIX semantics fixup system calls. There is a limited number of
257 // arguments needed and the caller should use 0 for those not needed.
258 func (sc *syscaller) prctlwcall(prVal, v1, v2 uintptr) (int, error) {
259 r, _, err := sc.w3(syscall.SYS_PRCTL, prVal, v1, v2)
260 if err != 0 {
261 return int(r), err
262 }
263 return int(r), nil
264 }
265
266 // prctlwcall6 provides a wrapper for the prctl systemcalls that
267 // write/modify kernel state and require 6 arguments - ambient cap
268 // API, I'm looking at you. (Where available, these will use the POSIX
269 // semantics fixup system calls). There is a limited number of
270 // arguments needed and the caller should use 0 for those not needed.
271 func (sc *syscaller) prctlwcall6(prVal, v1, v2, v3, v4, v5 uintptr) (int, error) {
272 r, _, err := sc.w6(syscall.SYS_PRCTL, prVal, v1, v2, v3, v4, v5)
273 if err != 0 {
274 return int(r), err
275 }
276 return int(r), nil
277 }
278
279 // cInit performs the lazy identification of the capability vintage of
280 // the running system.
281 func (sc *syscaller) cInit() {
282 h := &header{
283 magic: kv3,
284 }
285 sc.caprcall(syscall.SYS_CAPGET, h, nil)
286 magic = h.magic
287 switch magic {
288 case kv1:
289 words = 1
290 case kv2, kv3:
291 words = 2
292 default:
293 // Fall back to a known good version.
294 magic = kv3
295 words = 2
296 }
297 // Use the bounding set to evaluate which capabilities exist.
298 maxValues = uint(sort.Search(32*words, func(n int) bool {
299 _, err := GetBound(Value(n))
300 return err != nil
301 }))
302 if maxValues == 0 {
303 // Fall back to using the largest value defined at build time.
304 maxValues = NamedCount
305 }
306 }
307
308 // MaxBits returns the number of kernel-named capabilities discovered
309 // at runtime in the current system.
310 func MaxBits() Value {
311 startUp.Do(multisc.cInit)
312 return Value(maxValues)
313 }
314
315 // NewSet returns an empty capability set.
316 func NewSet() *Set {
317 startUp.Do(multisc.cInit)
318 return &Set{
319 flat: make([]data, words),
320 }
321 }
322
323 // ErrBadSet indicates a nil pointer was used for a *Set, or the
324 // request of the Set is invalid in some way.
325 var ErrBadSet = errors.New("bad capability set")
326
327 // good confirms that c looks valid.
328 func (c *Set) good() error {
329 if c == nil || len(c.flat) == 0 {
330 return ErrBadSet
331 }
332 return nil
333 }
334
335 // Dup returns a copy of the specified capability set.
336 func (c *Set) Dup() (*Set, error) {
337 if err := c.good(); err != nil {
338 return nil, err
339 }
340 n := NewSet()
341 c.mu.RLock()
342 defer c.mu.RUnlock()
343 copy(n.flat, c.flat)
344 n.nsRoot = c.nsRoot
345 return n, nil
346 }
347
348 // GetPID returns the capability set associated with the target process
349 // id; pid=0 is an alias for current.
350 func GetPID(pid int) (*Set, error) {
351 v := NewSet()
352 if err := multisc.caprcall(syscall.SYS_CAPGET, &header{magic: magic, pid: int32(pid)}, v.flat); err != nil {
353 return nil, err
354 }
355 return v, nil
356 }
357
358 // GetProc returns the capability Set of the current process. If the
359 // kernel is unable to determine the Set associated with the current
360 // process, the function panic()s.
361 func GetProc() *Set {
362 c, err := GetPID(0)
363 if err != nil {
364 panic(err)
365 }
366 return c
367 }
368
369 // setProc uses syscaller to set process capabilities. Note, c is
370 // either private to or (read) locked by the caller.
371 func (sc *syscaller) setProc(c *Set) error {
372 return sc.capwcall(syscall.SYS_CAPSET, &header{magic: magic}, c.flat)
373 }
374
375 // SetProc attempts to set the capability Set of the current
376 // process. The kernel will perform permission checks and an error
377 // will be returned if the attempt fails. Should the attempt fail
378 // no process capabilities will have been modified.
379 //
380 // Note, the general behavior of this call is to set the
381 // process-shared capabilities. However, when called from a callback
382 // function as part of a (*Launcher).Launch(), the call only sets the
383 // capabilities of the thread being used to perform the launch.
384 func (c *Set) SetProc() error {
385 if err := c.good(); err != nil {
386 return err
387 }
388 state, sc := scwStateSC()
389 defer scwSetState(launchBlocked, state, -1)
390 c.mu.RLock()
391 defer c.mu.RUnlock()
392 return sc.setProc(c)
393 }
394
395 // defines from uapi/linux/prctl.h
396 const (
397 prCapBSetRead = 23
398 prCapBSetDrop = 24
399 )
400
401 // GetBound determines if a specific capability is currently part of
402 // the local bounding set. On systems where the bounding set Value is
403 // not present, this function returns an error.
404 func GetBound(val Value) (bool, error) {
405 v, err := multisc.prctlrcall(prCapBSetRead, uintptr(val), 0)
406 if err != nil {
407 return false, err
408 }
409 return v > 0, nil
410 }
411
412 //go:uintptrescapes
413 func (sc *syscaller) dropBound(val ...Value) error {
414 for _, v := range val {
415 if _, err := sc.prctlwcall(prCapBSetDrop, uintptr(v), 0); err != nil {
416 return err
417 }
418 }
419 return nil
420 }
421
422 // DropBound attempts to suppress bounding set Values. The kernel will
423 // never allow a bounding set Value bit to be raised once successfully
424 // dropped. However, dropping requires the current process is
425 // sufficiently capable (usually via cap.SETPCAP being raised in the
426 // Effective flag of the process' Set). Note, the drops are performed
427 // in order and if one bounding value cannot be dropped, the function
428 // returns immediately with an error which may leave the system in an
429 // ill-defined state. The caller can determine where things went wrong
430 // using GetBound().
431 func DropBound(val ...Value) error {
432 state, sc := scwStateSC()
433 defer scwSetState(launchBlocked, state, -1)
434 return sc.dropBound(val...)
435 }
436
437 // defines from uapi/linux/prctl.h
438 const (
439 prCapAmbient = 47
440
441 prCapAmbientIsSet = 1
442 prCapAmbientRaise = 2
443 prCapAmbientLower = 3
444 prCapAmbientClearAll = 4
445 )
446
447 // GetAmbient determines if a specific capability is currently part of
448 // the local ambient set. On systems where the ambient set Value is
449 // not present, this function returns an error.
450 func GetAmbient(val Value) (bool, error) {
451 r, err := multisc.prctlrcall6(prCapAmbient, prCapAmbientIsSet, uintptr(val), 0, 0, 0)
452 return r > 0, err
453 }
454
455 //go:uintptrescapes
456 func (sc *syscaller) setAmbient(enable bool, val ...Value) error {
457 dir := uintptr(prCapAmbientLower)
458 if enable {
459 dir = prCapAmbientRaise
460 }
461 for _, v := range val {
462 _, err := sc.prctlwcall6(prCapAmbient, dir, uintptr(v), 0, 0, 0)
463 if err != nil {
464 return err
465 }
466 }
467 return nil
468 }
469
470 // SetAmbient attempts to set a specific Value bit to the state,
471 // enable. This function will return an error if insufficient
472 // permission is available to perform this task. The settings are
473 // performed in order and the function returns immediately an error is
474 // detected. Use GetAmbient() to unravel where things went
475 // wrong.
476 //
477 // Note, the cap package manages an abstraction IAB that captures all
478 // three inheritable vectors in a single type. Consider using that.
479 func SetAmbient(enable bool, val ...Value) error {
480 state, sc := scwStateSC()
481 defer scwSetState(launchBlocked, state, -1)
482 return sc.setAmbient(enable, val...)
483 }
484
485 func (sc *syscaller) resetAmbient() error {
486 var v bool
487 var err error
488
489 for c := Value(0); !v; c++ {
490 if v, err = GetAmbient(c); err != nil {
491 // no non-zero values found.
492 return nil
493 }
494 }
495 _, err = sc.prctlwcall6(prCapAmbient, prCapAmbientClearAll, 0, 0, 0, 0)
496 return err
497 }
498
499 // ResetAmbient attempts to ensure the Ambient set is fully
500 // cleared. It works by first reading the set and if it finds any bits
501 // raised it will attempt a reset. The test before attempting a reset
502 // behavior is a workaround for situations where the Ambient API is
503 // locked, but a reset is not actually needed. No Ambient bit not
504 // already raised in both the Permitted and Inheritable Set is allowed
505 // to be raised by the kernel.
506 func ResetAmbient() error {
507 state, sc := scwStateSC()
508 defer scwSetState(launchBlocked, state, -1)
509 return sc.resetAmbient()
510 }