Debian Codegraph @

cap/iab.go

raw
1 package cap
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "strconv"
7 "strings"
8 "sync"
9 )
10
11 // omask returns the offset and mask for a specific capability.
12 func omask(c Value) (uint, uint32) {
13 u := uint(c)
14 return u >> 5, uint32(1) << (u & 31)
15 }
16
17 // IAB holds a summary of all of the inheritable capability vectors:
18 // Inh, Amb and Bound. The Bound vector is the logical inverse (two's
19 // complement) of the process' Bounding set. That is, raising a Value
20 // in the Bound (think blocked) vector is equivalent to dropping that
21 // Value from the process' Bounding set. This convention is used to
22 // support the empty IAB as being mostly harmless.
23 type IAB struct {
24 mu sync.RWMutex
25 a, i, nb []uint32
26 }
27
28 // Vector enumerates which of the inheritable IAB capability vectors
29 // is being manipulated.
30 type Vector uint
31
32 // Inh, Amb, Bound enumerate the IAB vector components. (Vector) Inh
33 // is equivalent to (Flag) Inheritable. They are named differently for
34 // syntax/type checking reasons.
35 const (
36 Inh Vector = iota
37 Amb
38 Bound
39 )
40
41 // IABDiff holds the non-error result of an (*IAB).Cf()
42 // function call. It can be interpreted with the function
43 // (IABDiff).Has().
44 type IABDiff uint
45
46 // iBits, iBits and bBits track the (semi-)independent parts of an
47 // IABDiff.
48 const (
49 iBits IABDiff = 1 << Inh
50 aBits IABDiff = 1 << Amb
51 bBits IABDiff = 1 << Bound
52 )
53
54 // Has determines if an IAB comparison differs in a specific vector.
55 func (d IABDiff) Has(v Vector) bool {
56 return d&(1<<v) != 0
57 }
58
59 // String identifies a Vector value by its conventional I A or B
60 // string abbreviation.
61 func (v Vector) String() string {
62 switch v {
63 case Inh:
64 return "I"
65 case Amb:
66 return "A"
67 case Bound:
68 return "B"
69 default:
70 return "<Error>"
71 }
72 }
73
74 // NewIAB returns an empty IAB.
75 func NewIAB() *IAB {
76 startUp.Do(multisc.cInit)
77 return &IAB{
78 i: make([]uint32, words),
79 a: make([]uint32, words),
80 nb: make([]uint32, words),
81 }
82 }
83
84 // good confirms the iab looks to be initialized.
85 func (iab *IAB) good() error {
86 if iab == nil || len(iab.i) == 0 || len(iab.i) != words || len(iab.a) != words || len(iab.nb) != words {
87 return ErrBadValue
88 }
89 return nil
90 }
91
92 // Dup returns a duplicate copy of the IAB.
93 func (iab *IAB) Dup() (*IAB, error) {
94 if err := iab.good(); err != nil {
95 return nil, err
96 }
97 v := NewIAB()
98 iab.mu.RLock()
99 defer iab.mu.RUnlock()
100 copy(v.i, iab.i)
101 copy(v.a, iab.a)
102 copy(v.nb, iab.nb)
103 return v, nil
104 }
105
106 // IABInit allocates a new IAB tuple.
107 //
108 // Deprecated: Replace with NewIAB.
109 //
110 // Example, replace this:
111 //
112 // iab := IABInit()
113 //
114 // with this:
115 //
116 // iab := NewIAB()
117 func IABInit() *IAB {
118 return NewIAB()
119 }
120
121 // IABGetProc summarizes the Inh, Amb and Bound capability vectors of
122 // the current process.
123 func IABGetProc() *IAB {
124 iab := NewIAB()
125 current := GetProc()
126 iab.Fill(Inh, current, Inheritable)
127 for c := MaxBits(); c > 0; {
128 c--
129 offset, mask := omask(c)
130 if a, _ := GetAmbient(c); a {
131 iab.a[offset] |= mask
132 }
133 if b, err := GetBound(c); err == nil && !b {
134 iab.nb[offset] |= mask
135 }
136 }
137 return iab
138 }
139
140 // IABFromText parses a string representing an IAB, as generated
141 // by IAB.String(), to generate an IAB.
142 func IABFromText(text string) (*IAB, error) {
143 iab := NewIAB()
144 if len(text) == 0 {
145 return iab, nil
146 }
147 for _, f := range strings.Split(text, ",") {
148 var i, a, nb bool
149 var j int
150 for j = 0; j < len(f); j++ {
151 switch f[j : j+1] {
152 case "!":
153 nb = true
154 case "^":
155 i = true
156 a = true
157 case "%":
158 i = true
159 default:
160 goto done
161 }
162 }
163 done:
164 c, err := FromName(f[j:])
165 if err != nil {
166 return nil, err
167 }
168 offset, mask := omask(c)
169 if i || !nb {
170 iab.i[offset] |= mask
171 }
172 if a {
173 iab.a[offset] |= mask
174 }
175 if nb {
176 iab.nb[offset] |= mask
177 }
178 }
179 return iab, nil
180 }
181
182 // String serializes an IAB to a string format.
183 func (iab *IAB) String() string {
184 if err := iab.good(); err != nil {
185 return "<invalid>"
186 }
187 var vs []string
188 iab.mu.RLock()
189 defer iab.mu.RUnlock()
190 for c := Value(0); c < Value(maxValues); c++ {
191 offset, mask := omask(c)
192 i := (iab.i[offset] & mask) != 0
193 a := (iab.a[offset] & mask) != 0
194 nb := (iab.nb[offset] & mask) != 0
195 var cs []string
196 if nb {
197 cs = append(cs, "!")
198 }
199 if a {
200 cs = append(cs, "^")
201 } else if nb && i {
202 cs = append(cs, "%")
203 }
204 if nb || a || i {
205 vs = append(vs, strings.Join(cs, "")+c.String())
206 }
207 }
208 return strings.Join(vs, ",")
209 }
210
211 // iabSetProc uses a syscaller to apply an IAB tuple to the process.
212 // The iab is known to be locked by the caller.
213 func (sc *syscaller) iabSetProc(iab *IAB) (err error) {
214 temp := GetProc()
215 raising := false
216 bounder := false
217 for i := 0; i < words; i++ {
218 newI := iab.i[i]
219 oldIP := temp.flat[i][Inheritable] | temp.flat[i][Permitted]
220 raising = raising || (newI & ^oldIP != 0)
221 if iab.nb[i] != 0 {
222 bounder = true
223 }
224 temp.flat[i][Inheritable] = newI
225 }
226 if bounder {
227 bounder = false
228 for c := Value(maxValues); c > 0; {
229 c--
230 offset, mask := omask(c)
231 if iab.nb[offset]&mask == 0 {
232 continue
233 }
234 if b, _ := GetBound(c); b {
235 bounder = true
236 raising = true
237 break
238 }
239 }
240 }
241 working, err2 := temp.Dup()
242 if err2 != nil {
243 err = err2
244 return
245 }
246 if raising {
247 if err = working.SetFlag(Effective, true, SETPCAP); err != nil {
248 return
249 }
250 }
251 if err = sc.setProc(working); err != nil {
252 return
253 }
254 defer func() {
255 if err2 := sc.setProc(temp); err == nil {
256 err = err2
257 }
258 }()
259 if err = sc.resetAmbient(); err != nil {
260 return
261 }
262 for c := Value(maxValues); c > 0; {
263 c--
264 offset, mask := omask(c)
265 if iab.a[offset]&mask != 0 {
266 err = sc.setAmbient(true, c)
267 }
268 if bounder && err == nil && iab.nb[offset]&mask != 0 {
269 err = sc.dropBound(c)
270 }
271 if err != nil {
272 return
273 }
274 }
275 return
276 }
277
278 // SetProc attempts to change the Inheritable, Ambient and Bounding
279 // capability vectors of the current process using the content,
280 // iab. The Bounding vector strongly affects the potential for setting
281 // other bits, so this function carefully performs the combined
282 // operation in the most flexible manner. If the desired IAB value
283 // will change the Bounding value, cap.SETPCAP must be a Permitted
284 // value.
285 func (iab *IAB) SetProc() error {
286 if err := iab.good(); err != nil {
287 return err
288 }
289 state, sc := scwStateSC()
290 defer scwSetState(launchBlocked, state, -1)
291 iab.mu.RLock()
292 defer iab.mu.RUnlock()
293 return sc.iabSetProc(iab)
294 }
295
296 // GetVector returns the raised state of the specific capability bit
297 // of the indicated vector.
298 func (iab *IAB) GetVector(vec Vector, val Value) (bool, error) {
299 if err := iab.good(); err != nil {
300 return false, err
301 }
302 if val >= MaxBits() {
303 return false, ErrBadValue
304 }
305 iab.mu.RLock()
306 defer iab.mu.RUnlock()
307 offset, mask := omask(val)
308 switch vec {
309 case Inh:
310 return (iab.i[offset] & mask) != 0, nil
311 case Amb:
312 return (iab.a[offset] & mask) != 0, nil
313 case Bound:
314 return (iab.nb[offset] & mask) != 0, nil
315 default:
316 return false, ErrBadValue
317 }
318 }
319
320 // SetVector sets all of the vals in the specified vector to the
321 // raised value. Note, the Ambient vector cannot contain values not raised
322 // in the Inh vector, so setting values directly in one vector may have
323 // the side effect of mirroring the value in the other vector to
324 // maintain this constraint. Note, raising a Bound vector bit is
325 // equivalent to lowering the Bounding vector of the process (when
326 // successfully applied with (*IAB).SetProc()).
327 func (iab *IAB) SetVector(vec Vector, raised bool, vals ...Value) error {
328 if err := iab.good(); err != nil {
329 return err
330 }
331 iab.mu.Lock()
332 defer iab.mu.Unlock()
333 for _, val := range vals {
334 if val >= Value(maxValues) {
335 return ErrBadValue
336 }
337 offset, mask := omask(val)
338 switch vec {
339 case Inh:
340 if raised {
341 iab.i[offset] |= mask
342 } else {
343 iab.i[offset] &= ^mask
344 iab.a[offset] &= ^mask
345 }
346 case Amb:
347 if raised {
348 iab.a[offset] |= mask
349 iab.i[offset] |= mask
350 } else {
351 iab.a[offset] &= ^mask
352 }
353 case Bound:
354 if raised {
355 iab.nb[offset] |= mask
356 } else {
357 iab.nb[offset] &= ^mask
358 }
359 default:
360 return ErrBadValue
361 }
362 }
363 return nil
364 }
365
366 // Fill fills one of the Inh, Amb and Bound capability vectors from
367 // one of the flag vectors of a Set. Note, filling the Inh vector
368 // will mask the Amb vector, and filling the Amb vector may raise
369 // entries in the Inh vector. Further, when filling the Bound vector,
370 // the bits are inverted from what you might expect - that is lowered
371 // bits from the Set will be raised in the Bound vector.
372 func (iab *IAB) Fill(vec Vector, c *Set, flag Flag) error {
373 if err := iab.good(); err != nil {
374 return err
375 }
376 // work with a copy to avoid potential deadlock.
377 s, err := c.Dup()
378 if err != nil {
379 return err
380 }
381 iab.mu.Lock()
382 defer iab.mu.Unlock()
383 for i := 0; i < words; i++ {
384 flat := s.flat[i][flag]
385 switch vec {
386 case Inh:
387 iab.i[i] = flat
388 iab.a[i] &= flat
389 case Amb:
390 iab.a[i] = flat
391 iab.i[i] |= flat
392 case Bound:
393 iab.nb[i] = ^flat
394 default:
395 return ErrBadSet
396 }
397 }
398 return nil
399 }
400
401 // Cf compares two IAB values. Its return value is 0 if the compared
402 // tuples are considered identical. The macroscopic differences can be
403 // investigated with (IABDiff).Has().
404 func (iab *IAB) Cf(alt *IAB) (IABDiff, error) {
405 if err := iab.good(); err != nil {
406 return 0, err
407 }
408 if iab == alt {
409 return 0, nil
410 }
411 // Avoid holding two locks at once.
412 ref, err := alt.Dup()
413 if err != nil {
414 return 0, err
415 }
416 iab.mu.RLock()
417 defer iab.mu.RUnlock()
418
419 var cf IABDiff
420 for i := 0; i < words; i++ {
421 if iab.i[i] != ref.i[i] {
422 cf |= iBits
423 }
424 if iab.a[i] != ref.a[i] {
425 cf |= aBits
426 }
427 if iab.nb[i] != ref.nb[i] {
428 cf |= bBits
429 }
430 }
431 return cf, nil
432 }
433
434 // parseHex converts the /proc/*/status string into an array of
435 // uint32s suitable for storage in an IAB structure.
436 func parseHex(hex string, invert bool) []uint32 {
437 if len(hex) != 8*words {
438 // Invalid string
439 return nil
440 }
441 var result []uint32
442 for i := 0; i < words; i++ {
443 upper := 8 * (words - i)
444 raw, err := strconv.ParseUint(hex[upper-8:upper], 16, 32)
445 if err != nil {
446 return nil
447 }
448 if invert {
449 raw = ^raw
450 }
451 bits := allMask(uint(i)) & uint32(raw)
452 result = append(result, bits)
453 }
454 return result
455 }
456
457 var procRoot = "/proc"
458
459 // ProcRoot sets the local mount point for the Linux /proc filesystem.
460 // It defaults to "/proc", but might be mounted elsewhere on any given
461 // system. The function returns the previous value of the local mount
462 // point. If the user attempts to set it to "", the value is left
463 // unchanged.
464 func ProcRoot(path string) string {
465 was := procRoot
466 if path != "" {
467 procRoot = path
468 }
469 return was
470 }
471
472 // IABGetPID returns the IAB tuple of a specified process. The kernel
473 // ABI does not support this query via system calls, so the function
474 // works by parsing the /proc/<pid>/status file content.
475 func IABGetPID(pid int) (*IAB, error) {
476 tf := fmt.Sprintf("%s/%d/status", procRoot, pid)
477 d, err := ioutil.ReadFile(tf)
478 if err != nil {
479 return nil, err
480 }
481 iab := NewIAB()
482 for _, line := range strings.Split(string(d), "\n") {
483 if !strings.HasPrefix(line, "Cap") {
484 continue
485 }
486 flavor := line[3:]
487 if strings.HasPrefix(flavor, "Inh:\t") {
488 iab.i = parseHex(line[8:], false)
489 continue
490 }
491 if strings.HasPrefix(flavor, "Bnd:\t") {
492 iab.nb = parseHex(line[8:], true)
493 continue
494 }
495 if strings.HasPrefix(flavor, "Amb:\t") {
496 iab.a = parseHex(line[8:], false)
497 continue
498 }
499 }
500 if err := iab.good(); err != nil {
501 return nil, err
502 }
503 return iab, nil
504 }