apparmor

package
v0.0.0-...-bc60ea4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 20, 2024 License: GPL-3.0 Imports: 21 Imported by: 111

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ConfDir                string
	CacheDir               string
	SystemCacheDir         string
	SnapConfineAppArmorDir string
)
View Source
var LoadProfiles = func(fnames []string, cacheDir string, flags AaParserFlags) error {
	if len(fnames) == 0 {
		return nil
	}

	args := []string{"--replace", "--write-cache", fmt.Sprintf("--cache-loc=%s", cacheDir)}
	if flags&ConserveCPU != 0 {
		args = append(args, numberOfJobsParam())
	}

	if flags&SkipKernelLoad != 0 {
		args = append(args, "--skip-kernel-load")
	}

	if flags&SkipReadCache != 0 {
		args = append(args, "--skip-read-cache")
	}
	if !osutil.GetenvBool("SNAPD_DEBUG") {
		args = append(args, "--quiet")
	}

	cmd, _, err := AppArmorParser()
	if err != nil {
		return err
	}

	cmd.Args = append(cmd.Args, args...)
	cmd.Args = append(cmd.Args, fnames...)
	output, err := cmd.CombinedOutput()
	if err != nil || strings.Contains(string(output), "parser error") {
		if err == nil {

			err = fmt.Errorf("exit status 0 with parser error")
		}
		return fmt.Errorf("cannot load apparmor profiles: %s\napparmor_parser output:\n%s", err, string(output))
	}
	return nil
}

LoadProfiles loads apparmor profiles from the given files.

If no such profiles were previously loaded then they are simply added to the kernel. If there were some profiles with the same name before, those profiles are replaced.

View Source
var OverlayRootSnippet = `` /* 171-byte string literal not displayed */

OverlayRootSnippet contains the extra permissions necessary for snap and snap-confine to operate on systems where '/' is a writable overlay fs. AppArmor requires directory reads for upperdir (but these aren't otherwise visible to the snap). While we filter AppArmor regular expression (AARE) characters elsewhere, we double quote the path in case UPPERDIR has spaces.

View Source
var RemoteFSSnippet = `` /* 174-byte string literal not displayed */

RemoteFSSnippet contains extra permissions necessary for snaps and snap-confine to operate when remote file system, like nfs, is used. This is an imperfect solution as this grants some network access to all the snaps on the system. For tracking see https://bugs.launchpad.net/apparmor/+bug/1724903

View Source
var SnapConfineDistroProfilePath = func() string {

	for _, profileName := range []string{
		"usr.lib.snapd.snap-confine.real",
		"usr.lib.snapd.snap-confine",
		"usr.libexec.snapd.snap-confine",
	} {
		maybeProfilePath := filepath.Join(ConfDir, profileName)
		if osutil.FileExists(maybeProfilePath) {
			return maybeProfilePath
		}
	}

	return ""
}

SnapConfineDistroProfilePath returns the path to the AppArmor profile of the snap-confine binary shipped by the distribution package. If such a profile is not found (for instance, because we are running Ubuntu Core) return an empty string

Functions

func AppArmorParser

func AppArmorParser() (cmd *exec.Cmd, internal bool, err error)

AppArmorParser returns an exec.Cmd for the apparmor_parser binary, and a boolean to indicate whether this is internal to snapd (ie is provided by snapd)

func DecodeLabel

func DecodeLabel(label string) (snap, app, hook string, err error)

func GenerateAAREExclusionPatterns

func GenerateAAREExclusionPatterns(excludePatterns []string, opts *AAREExclusionPatternsOptions) (string, error)

GenerateAAREExclusionPatterns generates a series of valid AppArmor regular expression negation rules such that anything except the specific excludePatterns will match with the specified prefix and suffix rules. For example to allow reading any file except those matching /usr/*/foo, you would call this function with "/usr/*/foo" as the first argument, "" as the prefix and " r," as the suffix (the suffix being the main part of the read rule) and this function would return the following multi-line string with the relevant rules:

/[^u]** r, /u[^s]** r, /us[^r]** r, /usr[^/]** r, /usr/*/[^f]** r, /usr/*/f[^o]** r, /usr/*/fo[^o]** r,

This function only treats '*' specially in the string and does not handle any other alternations etc. that AARE may more generally support, and all patterns provided must be absolute filepaths that are at least 2 runes long.

This function also works with multiple exclude patterns such as specifying to exclude "/usr/lib/snapd" and "/var/lib/snapd" with suffix " r," would yield:

/[^uv]** r, /{u[^s],v[^a]}** r, /{us[^r],va[^r]}** r, /{usr[^/],var[^/]}** r, /{usr/[^l],var/[^l]}** r, /{usr/l[^i],var/l[^i]}** r, /{usr/li[^b],var/li[^b]}** r, /{usr/lib[^/],var/lib[^/]}** r, /{usr/lib/[^s],var/lib/[^s]}** r, /{usr/lib/s[^n],var/lib/s[^n]}** r, /{usr/lib/sn[^a],var/lib/sn[^a]}** r, /{usr/lib/sna[^p],var/lib/sna[^p]}** r, /{usr/lib/snap[^d],var/lib/snap[^d]}** r,

Note that with the previous rules, /usr/lib/snapdaemon would not match any rule

This function has the following limitations: The first character after a subpattern common to two or more excludePatterns cannot be '*' on any of the excludePatterns that share the common prefix. Eg. ["/snap/core/**", "/snap/*/core/**"] where '/snap/' would be the subpattern common to both excludePattern, and '*' would be the first character after the common subpattern in the second excludePattern. This is because there are no apparmor rules that can fulfill both requirements. For /snap/[^c]** -> It will also match /snap/a/core/** which should be excluded by the second pattern. For /snap/[^c*]** -> It will also exclude access to /snap/a/a that should be allowed as it is not explicitly excluded by any pattern

When the '*' is used to exclude suffixes, like in ["/*.bin"], rules should be generated in a reverse way:

/*[^n]{,/**} rw, /*[^i]n{,/**} rw, /*[^b]in{,/**} rw, /*[^.]bin{,/**} rw,

While generating those rules is technically possible, it will make the logic way more complex, thus the function would just return an error if a pattern of this kind is found. This functionality can be added in a subsequent PR if needed in the future

func InsertAAREExclusionPatterns

func InsertAAREExclusionPatterns(aaRules string, excludePatterns []string, opts *AAREExclusionPatternsOptions) (string, error)

InsertAAREExclusionPatterns replaces a ###EXCL{<pref>,<suf>}### snippet with matching prefix and comma separated suffixes with a set of rules generated by GenerateAAREExclusionPatterns.

func KernelFeatures

func KernelFeatures() ([]string, error)

KernelFeatures returns a sorted list of apparmor features like []string{"dbus", "network"}. The result is cached internally.

func LoadedProfiles

func LoadedProfiles() ([]string, error)

LoadedProfiles interrogates the kernel and returns a list of loaded apparmor profiles.

Snappy manages apparmor profiles named "snap.*". Other profiles might exist on the system (via snappy dimension) and those are filtered-out.

func MockFeatures

func MockFeatures(kernelFeatures []string, kernelError error, parserFeatures []string, parserError error) (restore func())

MockAppArmorFeatures makes the system believe it has certain kernel and parser features.

AppArmor level and summary are automatically re-assessed as needed on both the change and the restore process. Use this function to observe real assessment of arbitrary features.

func MockFsRootPath

func MockFsRootPath(path string) (restorer func())

func MockLevel

func MockLevel(level LevelType) (restore func())

MockAppArmorLevel makes the system believe it has certain level of apparmor support.

AppArmor kernel and parser features are set to unrealistic values that do not match the requested level. Use this function to observe behavior that relies solely on the apparmor level value.

func MockParserSearchPath

func MockParserSearchPath(new string) (restore func())

func ParserFeatures

func ParserFeatures() ([]string, error)

ParserFeatures returns a sorted list of apparmor parser features like []string{"unsafe", ...}. The computation is costly to perform. The result is cached internally.

func ParserMtime

func ParserMtime() int64

ParserMtime returns the mtime of the AppArmor parser, else 0.

func PromptingSupported

func PromptingSupported() (bool, string)

PromptingSupported returns true if prompting is supported by the system. Otherwise, returns false, along with a string explaining why prompting is unsupported.

func PromptingSupportedByFeatures

func PromptingSupportedByFeatures(apparmorFeatures *FeaturesSupported) (bool, string)

PromptingSupportedByFeatures returns whether prompting is supported by the given AppArmor kernel and parser features, and by the presence of the kernel notification socket.

func ReloadAllSnapProfiles

func ReloadAllSnapProfiles() error

ReloadAllSnapProfiles reload the AppArmor profiles of all installed snaps, as well as that of snap-confine. This method is meant to be called when some rules have been changed in AppArmor include files (like in the tunable files for HOMEDIRS or other variables) which are bound to affect most snaps.

func RemoveCachedProfiles

func RemoveCachedProfiles(names []string, cacheDir string) error

Remove any of the AppArmor profiles in names from the AppArmor cache in cacheDir

func RemoveSnapConfineSnippets

func RemoveSnapConfineSnippets() error

RemoveSnapConfineSnippets clears out any previously written apparmor snippets for snap-confine.

func SetupSnapConfineSnippets

func SetupSnapConfineSnippets() (wasChanged bool, err error)

SetupSnapConfineSnippets inspects the system and sets up local apparmor policy for snap-confine. Local policy is included by the system-wide policy. Returns whether any modifications was made to the snap-confine snippets.

func SnapAppFromPid

func SnapAppFromPid(pid int) (snap, app, hook string, err error)

func Summary

func Summary() string

Summary describes how well apparmor is supported on the current kernel. The computation is costly to perform. The result is cached internally.

func UpdateHomedirsTunable

func UpdateHomedirsTunable(homedirs []string) error

UpdateHomedirsTunable sets the AppArmor HOMEDIRS tunable to the list of the specified directories. This directly affects the value of the AppArmor @{HOME} variable. See the "/etc/apparmor.d/tunables/home" file for more information.

func ValidateNoAppArmorRegexp

func ValidateNoAppArmorRegexp(s string) error

ValidateNoAppArmorRegexp will check that the given string does not contain AppArmor regular expressions (AARE), double quotes or \0. Note that to check the inverse of this, that is that a string has valid AARE, one should use interfaces/utils.NewPathPattern().

Types

type AAREExclusionPatternsOptions

type AAREExclusionPatternsOptions struct {
	// Prefix is a string to include on every line in the permutations before
	// the exclusion permutation itself.
	Prefix string
	// Suffix is a string to include on every line in the permutations after
	// the exclusion permutation itself.
	Suffix string
}

type AaParserFlags

type AaParserFlags int
const (
	// SkipReadCache causes apparmor_parser to be invoked with --skip-read-cache.
	// This allows us to essentially overwrite a cache that we know is stale regardless
	// of the time and date settings (apparmor_parser caching is based on mtime).
	// Note that writing of the cache relies on --write-cache but we pass that
	// command-line option unconditionally.
	SkipReadCache AaParserFlags = 1 << iota

	// ConserveCPU tells apparmor_parser to spare up to two CPUs on multi-core systems to
	// reduce load when processing many profiles at once.
	ConserveCPU AaParserFlags = 1 << iota

	// SkipKernelLoad tells apparmor_parser not to load profiles into the kernel. The use
	// case of this is when in pre-seeding mode.
	SkipKernelLoad AaParserFlags = 1 << iota
)

type FeaturesSupported

type FeaturesSupported struct {
	KernelFeatures []string
	ParserFeatures []string
}

FeaturesSupported contains information about supported AppArmor kernel and parser features.

type LevelType

type LevelType int

LevelType encodes the kind of support for apparmor found on this system.

const (
	// Unknown indicates that apparmor was not probed yet.
	Unknown LevelType = iota
	// Unsupported indicates that apparmor is not enabled.
	Unsupported
	// Unusable indicates that apparmor is enabled but cannot be used.
	Unusable
	// Partial indicates that apparmor is enabled but some
	// features are missing.
	Partial
	// Full indicates that all features are supported.
	Full
)

func ProbedLevel

func ProbedLevel() LevelType

ProbedLevel quantifies how well apparmor is supported on the current kernel. The computation is costly to perform. The result is cached internally.

func (LevelType) String

func (level LevelType) String() string

Directories

Path Synopsis
Package notify implements high-level notify interface to a subset of AppArmor features
Package notify implements high-level notify interface to a subset of AppArmor features
listener
Package listener implements a high-level interface to the apparmor notification mechanism.
Package listener implements a high-level interface to the apparmor notification mechanism.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL