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

     1  // +build apparmor,linux
     2  
     3  package apparmor
     4  
     5  // #cgo LDFLAGS: -lapparmor
     6  // #include <sys/apparmor.h>
     7  // #include <stdlib.h>
     8  import "C"
     9  import (
    10  	"fmt"
    11  	"io/ioutil"
    12  	"os"
    13  	"unsafe"
    14  )
    15  
    16  // IsEnabled returns true if apparmor is enabled for the host.
    17  func IsEnabled() bool {
    18  	if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil && os.Getenv("container") == "" {
    19  		if _, err = os.Stat("/sbin/apparmor_parser"); err == nil {
    20  			buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
    21  			return err == nil && len(buf) > 1 && buf[0] == 'Y'
    22  		}
    23  	}
    24  	return false
    25  }
    26  
    27  // ApplyProfile will apply the profile with the specified name to the process after
    28  // the next exec.
    29  func ApplyProfile(name string) error {
    30  	if name == "" {
    31  		return nil
    32  	}
    33  	cName := C.CString(name)
    34  	defer C.free(unsafe.Pointer(cName))
    35  	if _, err := C.aa_change_onexec(cName); err != nil {
    36  		return fmt.Errorf("apparmor failed to apply profile: %s", err)
    37  	}
    38  	return nil
    39  }