2014-07-16 08:42:12 +08:00
|
|
|
// +build apparmor,linux
|
2014-06-10 06:52:12 +08:00
|
|
|
|
|
|
|
package apparmor
|
|
|
|
|
|
|
|
import (
|
2016-05-04 21:40:55 +08:00
|
|
|
"fmt"
|
2014-06-10 06:52:12 +08:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2015-07-02 00:55:46 +08:00
|
|
|
// IsEnabled returns true if apparmor is enabled for the host.
|
2014-06-10 06:52:12 +08:00
|
|
|
func IsEnabled() bool {
|
|
|
|
if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil && os.Getenv("container") == "" {
|
2015-04-14 23:18:31 +08:00
|
|
|
if _, err = os.Stat("/sbin/apparmor_parser"); err == nil {
|
|
|
|
buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
|
|
|
|
return err == nil && len(buf) > 1 && buf[0] == 'Y'
|
|
|
|
}
|
2014-06-10 06:52:12 +08:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2017-12-11 18:19:13 +08:00
|
|
|
func setprocattr(attr, value string) error {
|
|
|
|
// Under AppArmor you can only change your own attr, so use /proc/self/
|
|
|
|
// instead of /proc/<tid>/ like libapparmor does
|
|
|
|
path := fmt.Sprintf("/proc/self/attr/%s", attr)
|
|
|
|
|
|
|
|
f, err := os.OpenFile(path, os.O_WRONLY, 0)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
_, err = fmt.Fprintf(f, "%s", value)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// changeOnExec reimplements aa_change_onexec from libapparmor in Go
|
|
|
|
func changeOnExec(name string) error {
|
|
|
|
value := "exec " + name
|
|
|
|
if err := setprocattr("exec", value); err != nil {
|
|
|
|
return fmt.Errorf("apparmor failed to apply profile: %s", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-07-02 00:55:46 +08:00
|
|
|
// ApplyProfile will apply the profile with the specified name to the process after
|
|
|
|
// the next exec.
|
2014-06-10 06:52:12 +08:00
|
|
|
func ApplyProfile(name string) error {
|
|
|
|
if name == "" {
|
|
|
|
return nil
|
|
|
|
}
|
2017-12-11 18:19:13 +08:00
|
|
|
|
|
|
|
return changeOnExec(name)
|
2014-06-10 06:52:12 +08:00
|
|
|
}
|