github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/mergeCode/runc/libcontainer/capabilities_linux.go (about)

     1  // +build linux
     2  
     3  package libcontainer
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"strings"
     9  
    10  	"github.com/syndtr/gocapability/capability"
    11  )
    12  
    13  var capabilityMap map[string]capability.Cap
    14  
    15  func init() {
    16  	capabilityMap = make(map[string]capability.Cap)
    17  	last := capability.CAP_LAST_CAP
    18  	// workaround for RHEL6 which has no /proc/sys/kernel/cap_last_cap
    19  	if last == capability.Cap(63) {
    20  		last = capability.CAP_BLOCK_SUSPEND
    21  	}
    22  	for _, cap := range capability.List() {
    23  		if cap > last {
    24  			continue
    25  		}
    26  		capKey := fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String()))
    27  		capabilityMap[capKey] = cap
    28  	}
    29  }
    30  
    31  func newCapWhitelist(caps []string) (*whitelist, error) {
    32  	l := []capability.Cap{}
    33  	for _, c := range caps {
    34  		v, ok := capabilityMap[c]
    35  		if !ok {
    36  			return nil, fmt.Errorf("unknown capability %q", c)
    37  		}
    38  		l = append(l, v)
    39  	}
    40  	pid, err := capability.NewPid(os.Getpid())
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	return &whitelist{
    45  		keep: l,
    46  		pid:  pid,
    47  	}, nil
    48  }
    49  
    50  type whitelist struct {
    51  	pid  capability.Capabilities
    52  	keep []capability.Cap
    53  }
    54  
    55  // dropBoundingSet drops the capability bounding set to those specified in the whitelist.
    56  func (w *whitelist) dropBoundingSet() error {
    57  	w.pid.Clear(capability.BOUNDS)
    58  	w.pid.Set(capability.BOUNDS, w.keep...)
    59  	return w.pid.Apply(capability.BOUNDS)
    60  }
    61  
    62  // drop drops all capabilities for the current process except those specified in the whitelist.
    63  func (w *whitelist) drop() error {
    64  	w.pid.Clear(allCapabilityTypes)
    65  	w.pid.Set(allCapabilityTypes, w.keep...)
    66  	return w.pid.Apply(allCapabilityTypes)
    67  }