Debian Codegraph @

cap/file.go

raw
1 package cap
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "syscall"
11 "unsafe"
12 )
13
14 // uapi/linux/xattr.h defined.
15 var (
16 xattrNameCaps, _ = syscall.BytePtrFromString("security.capability")
17 )
18
19 // uapi/linux/capability.h defined.
20 const (
21 vfsCapRevisionMask = uint32(0xff000000)
22 vfsCapFlagsMask = ^vfsCapRevisionMask
23 vfsCapFlagsEffective = uint32(1)
24
25 vfsCapRevision1 = uint32(0x01000000)
26 vfsCapRevision2 = uint32(0x02000000)
27 vfsCapRevision3 = uint32(0x03000000)
28 )
29
30 // uapi/asm-generic/fcntl.h defined
31 const (
32 O_PATH = 0x200000
33 )
34
35 // Data types stored in little-endian order.
36
37 type vfsCaps1 struct {
38 MagicEtc uint32
39 Data [1]struct {
40 Permitted, Inheritable uint32
41 }
42 }
43
44 type vfsCaps2 struct {
45 MagicEtc uint32
46 Data [2]struct {
47 Permitted, Inheritable uint32
48 }
49 }
50
51 type vfsCaps3 struct {
52 MagicEtc uint32
53 Data [2]struct {
54 Permitted, Inheritable uint32
55 }
56 RootID uint32
57 }
58
59 // ErrBadSize indicates the loaded file capability has
60 // an invalid number of bytes in it.
61 var ErrBadSize = errors.New("filecap bad size")
62
63 // ErrBadMagic indicates that the kernel preferred magic number for
64 // capability Set values is not supported by this package. This
65 // generally implies you are using an exceptionally old
66 // "../libcap/cap" package. An upgrade is needed, or failing that see
67 // [the Fully Capable site] for the way to report or review a bug.
68 //
69 // [the Fully Capable site]: https://sites.google.com/site/fullycapable/
70 var ErrBadMagic = errors.New("unsupported magic")
71
72 // ErrBadPath indicates a failed attempt to set a file capability on
73 // an irregular (non-executable) file.
74 var ErrBadPath = errors.New("file is not a regular executable")
75
76 // ErrOutOfRange indicates an erroneous value for MinExtFlagSize.
77 var ErrOutOfRange = errors.New("flag length invalid for export")
78
79 // digestFileCap unpacks a file capability and returns it in a *Set
80 // form.
81 func digestFileCap(d []byte, sz int, err error) (*Set, error) {
82 if err != nil {
83 return nil, err
84 }
85 var raw1 vfsCaps1
86 var raw2 vfsCaps2
87 var raw3 vfsCaps3
88 if sz < binary.Size(raw1) || sz > binary.Size(raw3) {
89 return nil, ErrBadSize
90 }
91 b := bytes.NewReader(d[:sz])
92 var magicEtc uint32
93 if err = binary.Read(b, binary.LittleEndian, &magicEtc); err != nil {
94 return nil, err
95 }
96
97 c := NewSet()
98 b.Seek(0, io.SeekStart)
99 switch magicEtc & vfsCapRevisionMask {
100 case vfsCapRevision1:
101 if err = binary.Read(b, binary.LittleEndian, &raw1); err != nil {
102 return nil, err
103 }
104 data := raw1.Data[0]
105 c.flat[0][Permitted] = data.Permitted
106 c.flat[0][Inheritable] = data.Inheritable
107 if raw1.MagicEtc&vfsCapFlagsMask == vfsCapFlagsEffective {
108 c.flat[0][Effective] = data.Inheritable | data.Permitted
109 }
110 case vfsCapRevision2:
111 if err = binary.Read(b, binary.LittleEndian, &raw2); err != nil {
112 return nil, err
113 }
114 for i, data := range raw2.Data {
115 c.flat[i][Permitted] = data.Permitted
116 c.flat[i][Inheritable] = data.Inheritable
117 if raw2.MagicEtc&vfsCapFlagsMask == vfsCapFlagsEffective {
118 c.flat[i][Effective] = data.Inheritable | data.Permitted
119 }
120 }
121 case vfsCapRevision3:
122 if err = binary.Read(b, binary.LittleEndian, &raw3); err != nil {
123 return nil, err
124 }
125 for i, data := range raw3.Data {
126 c.flat[i][Permitted] = data.Permitted
127 c.flat[i][Inheritable] = data.Inheritable
128 if raw3.MagicEtc&vfsCapFlagsMask == vfsCapFlagsEffective {
129 c.flat[i][Effective] = data.Inheritable | data.Permitted
130 }
131 }
132 c.nsRoot = int(raw3.RootID)
133 default:
134 return nil, ErrBadMagic
135 }
136 return c, nil
137 }
138
139 //go:uintptrescapes
140
141 // GetFd returns the file capabilities of an open (*os.File).Fd().
142 func GetFd(file *os.File) (*Set, error) {
143 var raw3 vfsCaps3
144 d := make([]byte, binary.Size(raw3))
145 sz, _, oErr := multisc.r6(syscall.SYS_FGETXATTR, fd(file), uintptr(unsafe.Pointer(xattrNameCaps)), uintptr(unsafe.Pointer(&d[0])), uintptr(len(d)), 0, 0)
146 var err error
147 if oErr != 0 {
148 err = oErr
149 }
150 return digestFileCap(d, int(sz), err)
151 }
152
153 //go:uintptrescapes
154
155 // GetFile returns the file capabilities of a named file.
156 func GetFile(path string) (*Set, error) {
157 p, err := syscall.BytePtrFromString(path)
158 if err != nil {
159 return nil, err
160 }
161 var raw3 vfsCaps3
162 d := make([]byte, binary.Size(raw3))
163 sz, _, oErr := multisc.r6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(xattrNameCaps)), uintptr(unsafe.Pointer(&d[0])), uintptr(len(d)), 0, 0)
164 if oErr != 0 {
165 err = oErr
166 }
167 return digestFileCap(d, int(sz), err)
168 }
169
170 // GetNSOwner returns the namespace owner UID of the capability Set.
171 func (c *Set) GetNSOwner() (int, error) {
172 if magic < kv3 {
173 return 0, ErrBadMagic
174 }
175 c.mu.RLock()
176 defer c.mu.RUnlock()
177 return c.nsRoot, nil
178 }
179
180 // SetNSOwner adds an explicit namespace owner UID to the capability
181 // Set. This is only honored when generating file capabilities, and is
182 // generally for use by a setup process when installing binaries that
183 // use file capabilities to become capable inside a namespace to be
184 // administered by that UID. If capability aware code within that
185 // namespace writes file capabilities without explicitly setting such
186 // a UID, the kernel will fix-up the capabilities to be specific to
187 // that owner. In this way, the kernel prevents filesystem
188 // capabilities from leaking out of that restricted namespace.
189 func (c *Set) SetNSOwner(uid int) {
190 c.mu.Lock()
191 defer c.mu.Unlock()
192 c.nsRoot = uid
193 }
194
195 // packFileCap transforms a system capability into a VFS form. Because
196 // of the way Linux stores capabilities in the file extended
197 // attributes, the process is a little lossy with respect to effective
198 // bits.
199 func (c *Set) packFileCap() ([]byte, error) {
200 c.mu.RLock()
201 defer c.mu.RUnlock()
202
203 var magic uint32
204 switch words {
205 case 1:
206 if c.nsRoot != 0 {
207 return nil, ErrBadSet // nsRoot not supported for single DWORD caps.
208 }
209 magic = vfsCapRevision1
210 case 2:
211 if c.nsRoot == 0 {
212 magic = vfsCapRevision2
213 break
214 }
215 magic = vfsCapRevision3
216 }
217 if magic == 0 {
218 return nil, ErrBadSize
219 }
220 eff := uint32(0)
221 for _, f := range c.flat {
222 eff |= (f[Permitted] | f[Inheritable]) & f[Effective]
223 }
224 if eff != 0 {
225 magic |= vfsCapFlagsEffective
226 }
227 b := new(bytes.Buffer)
228 binary.Write(b, binary.LittleEndian, magic)
229 for _, f := range c.flat {
230 binary.Write(b, binary.LittleEndian, f[Permitted])
231 binary.Write(b, binary.LittleEndian, f[Inheritable])
232 }
233 if c.nsRoot != 0 {
234 binary.Write(b, binary.LittleEndian, c.nsRoot)
235 }
236 return b.Bytes(), nil
237 }
238
239 // specialFile confirms that the open file descriptor is not a regular
240 // file.
241 func specialFile(filed uintptr) bool {
242 var stat syscall.Stat_t
243 if err := syscall.Fstat(int(filed), &stat); err != nil {
244 return false
245 }
246 return (stat.Mode & syscall.S_IFMT) != syscall.S_IFREG
247 }
248
249 //go:uintptrescapes
250
251 // setFiled sets the file capability of an open file descriptor.
252 func (c *Set) setFiled(filed uintptr) error {
253 if c == nil {
254 if _, _, err := multisc.r6(syscall.SYS_FREMOVEXATTR, filed, uintptr(unsafe.Pointer(xattrNameCaps)), 0, 0, 0, 0); err != 0 {
255 return err
256 }
257 return nil
258 }
259 c.mu.RLock()
260 defer c.mu.RUnlock()
261 d, err := c.packFileCap()
262 if err != nil {
263 return err
264 }
265 if specialFile(filed) {
266 return ErrBadPath
267 }
268 if _, _, err := multisc.r6(syscall.SYS_FSETXATTR, filed, uintptr(unsafe.Pointer(xattrNameCaps)), uintptr(unsafe.Pointer(&d[0])), uintptr(len(d)), 0, 0); err != 0 {
269 return err
270 }
271 return nil
272 }
273
274 // SetFd attempts to set the file capabilities of an open
275 // (*os.File).Fd(). This function can also be used to delete a file's
276 // capabilities, by calling with c = nil.
277 //
278 // Note, Linux does not store the full Effective Flag in the metadata
279 // for the file. Only a single Effective bit is stored in this
280 // metadata. This single bit is non-zero if the Effective Flag has any
281 // overlapping bits with the Permitted or Inheritable Flags of c. This
282 // may appear suboptimal, but the reasoning behind it is sound.
283 // Namely, the purpose of the Effective bit it to support capabability
284 // unaware binaries that will only work if they magically launch with
285 // the needed Values already raised (this bit is sometimes referred to
286 // simply as the 'legacy' bit).
287 //
288 // Historical note: without *full* support for runtime capability
289 // manipulation, as it is provided in this "../libcap/cap" package,
290 // this was previously the only way for Go programs to make use of
291 // file capabilities.
292 //
293 // The preferred way that a binary will actually manipulate its
294 // file-acquired capabilities is to carefully and deliberately use
295 // this package (or libcap, assisted by libpsx, for threaded C/C++
296 // family code).
297 func (c *Set) SetFd(file *os.File) error {
298 return c.setFiled(fd(file))
299 }
300
301 //go:uintptrescapes
302
303 // SetFile attempts to set the file capabilities of the specified
304 // filename. This function can also be used to delete a file's
305 // capabilities, by calling with c = nil.
306 //
307 // Note, see the comment for SetFd() for some non-obvious behavior of
308 // Linux for the Effective Flag on the modified file.
309 func (c *Set) SetFile(path string) error {
310 filed, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
311 if err == nil {
312 defer syscall.Close(filed)
313 return c.setFiled(uintptr(filed))
314 }
315
316 // Corner case: attempting to set a capability on a file not
317 // readable by the caller.
318
319 filed, err = syscall.Open(path, O_PATH|syscall.O_NOFOLLOW, 0)
320 if err != nil {
321 return err
322 }
323 defer syscall.Close(filed)
324 if specialFile(uintptr(filed)) {
325 return ErrBadPath
326 }
327 stable := fmt.Sprint(procRoot, "/self/fd/", filed)
328 p, err := syscall.BytePtrFromString(stable)
329 if err != nil {
330 return err
331 }
332 if c == nil {
333 if _, _, err := multisc.r6(syscall.SYS_REMOVEXATTR, uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(xattrNameCaps)), 0, 0, 0, 0); err != 0 {
334 return err
335 }
336 return nil
337 }
338 c.mu.RLock()
339 defer c.mu.RUnlock()
340 d, err := c.packFileCap()
341 if err != nil {
342 return err
343 }
344 if _, _, err := multisc.r6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(xattrNameCaps)), uintptr(unsafe.Pointer(&d[0])), uintptr(len(d)), 0, 0); err != 0 {
345 return err
346 }
347 return nil
348 }
349
350 // ExtMagic is the 32-bit (little endian) magic for an external
351 // capability set. It can be used to transmit capabilities in binary
352 // format in a Linux portable way. The format is:
353 // <ExtMagic><byte:length><length-bytes*3-of-cap-data>.
354 const ExtMagic = uint32(0x5101c290)
355
356 // Import imports a Set from a byte array where it has been stored in
357 // a portable (lossless) way. That is values exported by
358 // libcap.cap_copy_ext() and Export().
359 func Import(d []byte) (*Set, error) {
360 b := bytes.NewBuffer(d)
361 var m uint32
362 if err := binary.Read(b, binary.LittleEndian, &m); err != nil {
363 return nil, ErrBadSize
364 } else if m != ExtMagic {
365 return nil, ErrBadMagic
366 }
367 var n byte
368 if err := binary.Read(b, binary.LittleEndian, &n); err != nil {
369 return nil, ErrBadSize
370 }
371 c := NewSet()
372 if int(n) > 4*words {
373 return nil, ErrBadSize
374 }
375 f := make([]byte, 3)
376 for i := 0; i < words; i++ {
377 for j := uint(0); n > 0 && j < 4; j++ {
378 n--
379 if x, err := b.Read(f); err != nil || x != 3 {
380 return nil, ErrBadSize
381 }
382 sh := 8 * j
383 c.flat[i][Effective] |= uint32(f[0]) << sh
384 c.flat[i][Permitted] |= uint32(f[1]) << sh
385 c.flat[i][Inheritable] |= uint32(f[2]) << sh
386 }
387 }
388 return c, nil
389 }
390
391 // MinExtFlagSize defaults to 8 in order to be equivalent to libcap
392 // defaults. Setting it to zero can generate smaller external
393 // representations. Such smaller representations can be imported by
394 // libcap and the Go package just fine, we just default to the default
395 // libcap representation for legacy reasons.
396 var MinExtFlagSize = uint(8)
397
398 // Export exports a Set into a lossless byte array format where it is
399 // stored in a portable way. Note, any namespace owner in the Set
400 // content is not exported by this function.
401 //
402 // Note, Export() generates exported byte streams that are importable
403 // by libcap.cap_copy_int() as well as Import().
404 func (c *Set) Export() ([]byte, error) {
405 if err := c.good(); err != nil {
406 return nil, err
407 }
408 if MinExtFlagSize > 255 {
409 return nil, ErrOutOfRange
410 }
411 b := new(bytes.Buffer)
412 binary.Write(b, binary.LittleEndian, ExtMagic)
413 c.mu.RLock()
414 defer c.mu.RUnlock()
415 var n = uint(0)
416 for i, f := range c.flat {
417 if nn := 4 * uint(i); nn+4 > n {
418 if u := f[Effective] | f[Permitted] | f[Inheritable]; u != 0 {
419 n = nn
420 for ; u != 0; u >>= 8 {
421 n++
422 }
423 }
424 }
425 }
426 if n < MinExtFlagSize {
427 n = MinExtFlagSize
428 }
429 b.Write([]byte{byte(n)})
430 for _, f := range c.flat {
431 if n == 0 {
432 break
433 }
434 eff, per, inh := f[Effective], f[Permitted], f[Inheritable]
435 for i := 0; n > 0 && i < 4; i++ {
436 n--
437 b.Write([]byte{
438 byte(eff & 0xff),
439 byte(per & 0xff),
440 byte(inh & 0xff),
441 })
442 eff >>= 8
443 per >>= 8
444 inh >>= 8
445 }
446 }
447 for n > 0 {
448 n--
449 b.Write([]byte{0, 0, 0})
450 }
451 return b.Bytes(), nil
452 }