Skip to content

Commit

Permalink
apparmor profile includes files if they exist
Browse files Browse the repository at this point in the history
  • Loading branch information
tinnywang committed May 11, 2024
1 parent a8cdf58 commit ecbaf37
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions ecs-init/apparmor/apparmor.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
package apparmor

import (
"errors"
"fmt"
"html/template"
"os"
"path/filepath"

Expand All @@ -28,11 +30,22 @@ const (
appArmorProfileDir = "/etc/apparmor.d"
)

type profile struct {
IncludeTunablesGlobal bool
IncludeAbstractionsBase bool
}

const ecsAgentDefaultProfile = `
{{if .IncludeTunablesGlobal}}
#include <tunables/global>
{{else}}
@{PROC}=/proc/
{{end}}
profile ecs-agent-default flags=(attach_disconnected,mediate_deleted) {
{{if .IncludeAbstractionsBase}}
#include <abstractions/base>
{{end}}
network inet,
network inet6,
Expand Down Expand Up @@ -77,6 +90,7 @@ var (
isProfileLoaded = aaprofile.IsLoaded
loadPath = aaparser.LoadProfile
createFile = os.Create
statFile = os.Stat
)

// LoadDefaultProfile ensures the default profile to be loaded with the given name.
Expand All @@ -87,19 +101,45 @@ func LoadDefaultProfile(profileName string) error {
return err
}

includeTunablesGlobal, err := fileExists(filepath.Join(appArmorProfileDir, "tunables/global"))
if err != nil {
return err
}

includeAbstractionsBase, err := fileExists(filepath.Join(appArmorProfileDir, "abstractions/base"))
if err != nil {
return err
}

f, err := createFile(filepath.Join(appArmorProfileDir, profileName))
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(ecsAgentDefaultProfile)

t := template.Must(template.New("profile").Parse(ecsAgentDefaultProfile))
err = t.Execute(f, profile{
IncludeTunablesGlobal: includeTunablesGlobal,
IncludeAbstractionsBase: includeAbstractionsBase,
})
if err != nil {
return err
}
path := f.Name()

path := f.Name()
if err := loadPath(path); err != nil {
return fmt.Errorf("error loading apparmor profile %s: %w", path, err)
}
return nil
}

func fileExists(path string) (bool, error) {
_, err := statFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
return true, nil
}

0 comments on commit ecbaf37

Please sign in to comment.