This commit is contained in:
Alex 2024-11-04 19:18:22 +08:00 committed by GitHub
commit 76105e699c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
18 changed files with 537 additions and 90 deletions

View File

@ -7,7 +7,8 @@ DESTDIR ?= /
BUILD ?= .build BUILD ?= .build
PKGDEST ?= ${PWD}/.pkg PKGDEST ?= ${PWD}/.pkg
PKGNAME := apparmor.d PKGNAME := apparmor.d
PROFILES = $(filter-out dpkg,$(notdir $(wildcard ${BUILD}/apparmor.d/*))) PROFILE = $(filter-out dpkg,$(notdir $(wildcard ${BUILD}/apparmor.d/*)))
PROFILES = profiles-apparmor.d profiles-other $(patsubst dists/packages/%,profiles-%,$(basename $(wildcard dists/packages/*.conf)))
.PHONY: all .PHONY: all
all: build all: build
@ -26,32 +27,53 @@ enforce: build
full: build full: build
@./${BUILD}/prebuild --complain --full @./${BUILD}/prebuild --complain --full
.PHONY: packages
packages: clean build
@./${BUILD}/prebuild --complain --packages
# Install apparmor.d
.PHONY: install .PHONY: install
install: install: install-bin install-share install-systemd profiles-apparmor.d
# Install apparmor.d.base
.PHONY: install-base
install-base: install-bin install-share install-systemd profiles-base
.PHONY: install-bin
install-bin:
@install -Dm0755 ${BUILD}/aa-log ${DESTDIR}/usr/bin/aa-log @install -Dm0755 ${BUILD}/aa-log ${DESTDIR}/usr/bin/aa-log
.PHONY: install-share
install-share:
@for file in $(shell find "${BUILD}/share" -type f -not -name "*.md" -printf "%P\n"); do \ @for file in $(shell find "${BUILD}/share" -type f -not -name "*.md" -printf "%P\n"); do \
install -Dm0644 "${BUILD}/share/$${file}" "${DESTDIR}/usr/share/$${file}"; \ install -Dm0644 "${BUILD}/share/$${file}" "${DESTDIR}/usr/share/$${file}"; \
done; done;
@for file in $(shell find "${BUILD}/apparmor.d" -type f -printf "%P\n"); do \
install -Dm0644 "${BUILD}/apparmor.d/$${file}" "${DESTDIR}/etc/apparmor.d/$${file}"; \ .PHONY: install-systemd
done; install-systemd:
@for file in $(shell find "${BUILD}/apparmor.d" -type l -printf "%P\n"); do \
mkdir -p "${DESTDIR}/etc/apparmor.d/disable"; \
cp -d "${BUILD}/apparmor.d/$${file}" "${DESTDIR}/etc/apparmor.d/$${file}"; \
done;
@for file in ${BUILD}/systemd/system/*; do \ @for file in ${BUILD}/systemd/system/*; do \
service="$$(basename "$$file")"; \ service="$$(basename "$${file}")"; \
install -Dm0644 "$${file}" "${DESTDIR}/usr/lib/systemd/system/$${service}.d/apparmor.conf"; \ install -Dm0644 "$${file}" "${DESTDIR}/usr/lib/systemd/system/$${service}.d/apparmor.conf"; \
done; done;
@for file in ${BUILD}/systemd/user/*; do \ @for file in ${BUILD}/systemd/user/*; do \
service="$$(basename "$$file")"; \ service="$$(basename "$${file}")"; \
install -Dm0644 "$${file}" "${DESTDIR}/usr/lib/systemd/user/$${service}.d/apparmor.conf"; \ install -Dm0644 "$${file}" "${DESTDIR}/usr/lib/systemd/user/$${service}.d/apparmor.conf"; \
done done
# Install all profiles for a given (sub)package
.PHONY: $(PROFILES) .PHONY: $(PROFILES)
$(PROFILES): $(PROFILES):
@install -Dm0755 ${BUILD}/aa-log ${DESTDIR}/usr/bin/aa-log @for file in $(shell find "${BUILD}/$(patsubst profiles-%,%,$@)" -type f -printf "%P\n"); do \
install -Dm0644 "${BUILD}/$(patsubst profiles-%,%,$@)/$${file}" "${DESTDIR}/etc/apparmor.d/$${file}"; \
done;
@for file in $(shell find "${BUILD}/$(patsubst profiles-%,%,$@)" -type l -printf "%P\n"); do \
mkdir -p "${DESTDIR}/etc/apparmor.d/disable"; \
cp -d "${BUILD}/$(patsubst profiles-%,%,$@)/$${file}" "${DESTDIR}/etc/apparmor.d/$${file}"; \
done;
# Partial install (not recommended)
.PHONY: $(PROFILE)
$(PROFILE): install-bin
@for file in $(shell find ${BUILD}/apparmor.d/abstractions/ -type f -printf "%P\n"); do \ @for file in $(shell find ${BUILD}/apparmor.d/abstractions/ -type f -printf "%P\n"); do \
install -Dm0644 "${BUILD}/apparmor.d/abstractions/$${file}" "${DESTDIR}/etc/apparmor.d/abstractions/$${file}"; \ install -Dm0644 "${BUILD}/apparmor.d/abstractions/$${file}" "${DESTDIR}/etc/apparmor.d/abstractions/$${file}"; \
done; done;

View File

@ -3,19 +3,23 @@
# Warning: for development only, use https://aur.archlinux.org/packages/apparmor.d-git for production use. # Warning: for development only, use https://aur.archlinux.org/packages/apparmor.d-git for production use.
pkgname=apparmor.d pkgbase=apparmor.d
pkgver=0.001 pkgname=(
apparmor.d apparmor.d.base
apparmor.d.other
)
pkgver=0.0001
pkgrel=1 pkgrel=1
pkgdesc="Full set of apparmor profiles" pkgdesc="Full set of apparmor profiles (base)"
arch=("x86_64") arch=("any")
url="https://github.com/roddhjav/$pkgname" url="https://github.com/roddhjav/apparmor.d"
license=('GPL2') license=('GPL2')
depends=('apparmor') depends=('apparmor')
makedepends=('go' 'git' 'rsync') makedepends=('go' 'git' 'rsync')
conflicts=("$pkgname-git") conflicts=("$pkgbase-git" "$pkgbase")
pkgver() { pkgver() {
cd "$srcdir/$pkgname" cd "$srcdir/$pkgbase"
echo "0.$(git rev-list --count HEAD)" echo "0.$(git rev-list --count HEAD)"
} }
@ -24,16 +28,33 @@ prepare() {
} }
build() { build() {
cd "$srcdir/$pkgname" cd "$srcdir/$pkgbase"
export CGO_CPPFLAGS="${CPPFLAGS}" export CGO_CPPFLAGS="${CPPFLAGS}"
export CGO_CFLAGS="${CFLAGS}" export CGO_CFLAGS="${CFLAGS}"
export CGO_CXXFLAGS="${CXXFLAGS}" export CGO_CXXFLAGS="${CXXFLAGS}"
export CGO_LDFLAGS="${LDFLAGS}" export CGO_LDFLAGS="${LDFLAGS}"
export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw" export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw"
make DISTRIBUTION=arch make BUILD=.buid.all DISTRIBUTION=arch
make packages DISTRIBUTION=arch
} }
package() { package_apparmor.d() {
cd "$srcdir/$pkgname" pkgdesc="Full set of apparmor profiles"
make install DESTDIR="$pkgdir" arch=("$CARCH")
conflicts=("${pkgname[@]:1}")
cd "$srcdir/$pkgbase"
make install BUILD=.buid.all DESTDIR="$pkgdir"
}
package_apparmor.d.base() {
arch=("$CARCH")
cd "$srcdir/$pkgbase"
make install-base DESTDIR="$pkgdir"
}
package_apparmor.d.other() {
pkgdesc="Full set of apparmor profiles (other)"
depends=(apparmor.d.base)
cd "$srcdir/$pkgbase"
make profiles-other DESTDIR="$pkgdir"
} }

View File

@ -37,8 +37,6 @@ func init() {
// Compatibility with AppArmor 3 // Compatibility with AppArmor 3
switch prebuild.Distribution { switch prebuild.Distribution {
case "arch":
case "ubuntu": case "ubuntu":
if !slices.Contains([]string{"noble"}, prebuild.Release["VERSION_CODENAME"]) { if !slices.Contains([]string{"noble"}, prebuild.Release["VERSION_CODENAME"]) {
prebuild.ABI = 3 prebuild.ABI = 3

View File

@ -4,9 +4,6 @@ apparmor.d/groups/apt
# Ubuntu specific definition # Ubuntu specific definition
apparmor.d/groups/ubuntu apparmor.d/groups/ubuntu
# OpenSUSE specific definition
apparmor.d/groups/suse
# Whonix specific definition # Whonix specific definition
apparmor.d/groups/whonix apparmor.d/groups/whonix
apparmor.d/tunables/home.d/whonix apparmor.d/tunables/home.d/whonix

View File

@ -5,9 +5,6 @@ share/libalpm
# Ubuntu specific definition # Ubuntu specific definition
apparmor.d/groups/ubuntu apparmor.d/groups/ubuntu
# OpenSUSE specific definition
apparmor.d/groups/suse
# Whonix specific definition # Whonix specific definition
apparmor.d/groups/whonix apparmor.d/groups/whonix
apparmor.d/abstractions/base.anondist apparmor.d/abstractions/base.anondist

View File

@ -2,9 +2,6 @@
apparmor.d/groups/pacman apparmor.d/groups/pacman
share/libalpm share/libalpm
# OpenSUSE specific definition
apparmor.d/groups/suse
# Whonix specific definition # Whonix specific definition
apparmor.d/groups/whonix apparmor.d/groups/whonix
apparmor.d/tunables/home.d/whonix apparmor.d/tunables/home.d/whonix

View File

@ -2,9 +2,6 @@
apparmor.d/groups/pacman apparmor.d/groups/pacman
share/libalpm share/libalpm
# OpenSUSE specific definition
apparmor.d/groups/suse
# Whonix does not have them # Whonix does not have them
apparmor.d/groups/pacman apparmor.d/groups/pacman
apparmor.d/groups/ubuntu apparmor.d/groups/ubuntu

22
dists/packages/base.conf Normal file
View File

@ -0,0 +1,22 @@
# apparmor.d - Full set of apparmor profiles
# Copyright (C) 2024 Alexandre Pujol <alexandre@pujol.io>
# SPDX-License-Identifier: GPL-2.0-only
# Minimal core with tunables, abstractions, and dependencies of other profiles
mode=enforce
tunables
abstractions
!abstractions/app/chromium
!abstractions/app/firefox
groups/children
!groups/children/user_confined
!groups/children/user_default
!groups/children/user_unconfined
groups/bus
profiles-s-z/unix-chkpwd
profiles-m-r/pam-tmpdir-helper

View File

@ -6,6 +6,8 @@ package builder
import ( import (
"fmt" "fmt"
"slices"
"strings"
"github.com/roddhjav/apparmor.d/pkg/paths" "github.com/roddhjav/apparmor.d/pkg/paths"
"github.com/roddhjav/apparmor.d/pkg/prebuild" "github.com/roddhjav/apparmor.d/pkg/prebuild"
@ -33,7 +35,7 @@ type Option struct {
func NewOption(file *paths.Path) *Option { func NewOption(file *paths.Path) *Option {
return &Option{ return &Option{
Name: file.Base(), Name: strings.TrimSuffix(file.Base(), ".apparmor.d"),
File: file, File: file,
} }
} }
@ -41,13 +43,26 @@ func NewOption(file *paths.Path) *Option {
func Register(names ...string) { func Register(names ...string) {
for _, name := range names { for _, name := range names {
if b, present := Builders[name]; present { if b, present := Builders[name]; present {
if !slices.Contains(Builds, b) {
Builds = append(Builds, b) Builds = append(Builds, b)
}
} else { } else {
panic(fmt.Sprintf("Unknown builder: %s", name)) panic(fmt.Sprintf("Unknown builder: %s", name))
} }
} }
} }
func Unregister(names ...string) {
for _, name := range names {
for i, b := range Builds {
if b.Name() == name {
Builds = slices.Delete(Builds, i, i+1)
break
}
}
}
}
func RegisterBuilder(d Builder) { func RegisterBuilder(d Builder) {
Builders[d.Name()] = d Builders[d.Name()] = d
} }

View File

@ -15,21 +15,24 @@ import (
"github.com/roddhjav/apparmor.d/pkg/prebuild/builder" "github.com/roddhjav/apparmor.d/pkg/prebuild/builder"
"github.com/roddhjav/apparmor.d/pkg/prebuild/directive" "github.com/roddhjav/apparmor.d/pkg/prebuild/directive"
"github.com/roddhjav/apparmor.d/pkg/prebuild/prepare" "github.com/roddhjav/apparmor.d/pkg/prebuild/prepare"
"github.com/roddhjav/apparmor.d/pkg/util"
) )
const ( const (
nilABI uint = 0 nilABI uint = 0
usage = `aa-prebuild [-h] [--complain | --enforce] [--full] [--abi 3|4] usage = `aa-prebuild [-h] [-s] [--complain|--enforce] [--packages] [--full] [--abi 3|4]
Prebuild apparmor.d profiles for a given distribution and apply Prebuild apparmor.d profiles for a given distribution, apply
internal built-in directives. internal built-in directives and build sub-packages structure.
Options: Options:
-h, --help Show this help message and exit. -h, --help Show this help message and exit.
-c, --complain Set complain flag on all profiles. -c, --complain Set complain flag on all profiles.
-e, --enforce Set enforce flag on all profiles. -e, --enforce Set enforce flag on ALL profiles.
-a, --abi ABI Target apparmor ABI. -a, --abi ABI Target apparmor ABI.
-f, --full Set AppArmor for full system policy. -f, --full Set AppArmor for full system policy.
-p, --packages Build all split packages.
-s, --status Show build configuration.
-F, --file Only prebuild a given file. -F, --file Only prebuild a given file.
` `
) )
@ -39,6 +42,7 @@ var (
complain bool complain bool
enforce bool enforce bool
full bool full bool
packages bool
abi uint abi uint
file string file string
) )
@ -54,6 +58,8 @@ func init() {
flag.BoolVar(&enforce, "enforce", false, "Set enforce flag on all profiles.") flag.BoolVar(&enforce, "enforce", false, "Set enforce flag on all profiles.")
flag.UintVar(&abi, "a", nilABI, "Target apparmor ABI.") flag.UintVar(&abi, "a", nilABI, "Target apparmor ABI.")
flag.UintVar(&abi, "abi", nilABI, "Target apparmor ABI.") flag.UintVar(&abi, "abi", nilABI, "Target apparmor ABI.")
flag.BoolVar(&packages, "p", false, "Build all split packages.")
flag.BoolVar(&packages, "packages", false, "Build all split packages.")
flag.StringVar(&file, "F", "", "Only prebuild a given file.") flag.StringVar(&file, "F", "", "Only prebuild a given file.")
flag.StringVar(&file, "file", "", "Only prebuild a given file.") flag.StringVar(&file, "file", "", "Only prebuild a given file.")
} }
@ -79,12 +85,6 @@ func Prebuild() {
prepare.Register("systemd-early") prepare.Register("systemd-early")
} }
if complain {
builder.Register("complain")
} else if enforce {
builder.Register("enforce")
}
if abi != nilABI { if abi != nilABI {
prebuild.ABI = abi prebuild.ABI = abi
} }
@ -104,13 +104,32 @@ func Prebuild() {
overwrite.OneFile = true overwrite.OneFile = true
} }
logging.Step("Building apparmor.d profiles for %s on ABI%d.", prebuild.Distribution, prebuild.ABI) // Prepare the build directories
logging.Step("Building apparmor.d profiles for %s (abi%d).", prebuild.Distribution, prebuild.ABI)
prebuild.RootApparmord = prebuild.Root.Join(prebuild.Src)
if err := Prepare(); err != nil { if err := Prepare(); err != nil {
logging.Fatal("%s", err.Error()) logging.Fatal("%s", err.Error())
} }
// Generate the packages
if packages {
if err := Packages(); err != nil {
logging.Fatal("%s", err.Error())
}
}
// Build the apparmor.d profiles
if err := Build(); err != nil { if err := Build(); err != nil {
logging.Fatal("%s", err.Error()) logging.Fatal("%s", err.Error())
} }
if packages {
// Move all other profiles to apparmor.d.other
prebuild.RootApparmord = prebuild.Root.Join(prebuild.Src)
if err := prebuild.RootApparmord.Rename(prebuild.Root.Join("other")); err != nil {
logging.Fatal("%s", err.Error())
}
}
} }
func Prepare() error { func Prepare() error {
@ -136,7 +155,44 @@ func Prepare() error {
return nil return nil
} }
func Packages() error {
logging.Success("Building apparmor.d.* packages structure:")
for _, name := range prebuild.Packages {
pkg := prebuild.NewPackage(name)
msg, err := pkg.Generate()
if err != nil {
return err
}
if err = pkg.Validate(); err != nil {
return err
}
logging.Indent = " "
logging.Bullet("apparmor.d.%s", name)
logging.Indent += " "
for _, line := range util.RemoveDuplicate(msg) {
logging.Warning("%s", line)
}
logging.Indent = ""
}
return nil
}
func Build() error { func Build() error {
sources := []string{prebuild.Src}
if packages {
sources = append(sources, prebuild.Packages...)
}
for _, src := range sources {
prebuild.RootApparmord = prebuild.Root.Join(src)
if src == prebuild.Src {
setMode("")
} else {
pkg := prebuild.NewPackage(src)
setMode(pkg.Mode)
}
files, _ := prebuild.RootApparmord.ReadDirRecursiveFiltered(nil, paths.FilterOutDirectories()) files, _ := prebuild.RootApparmord.ReadDirRecursiveFiltered(nil, paths.FilterOutDirectories())
for _, file := range files { for _, file := range files {
if !file.Exist() { if !file.Exist() {
@ -158,6 +214,7 @@ func Build() error {
return err return err
} }
} }
}
logging.Success("Build tasks:") logging.Success("Build tasks:")
logging.Indent = " " logging.Indent = " "
@ -173,3 +230,20 @@ func Build() error {
logging.Indent = "" logging.Indent = ""
return nil return nil
} }
func setMode(mode string) {
if mode == "" {
if complain {
mode = "complain"
} else if enforce {
mode = "enforce"
}
}
switch mode {
case "complain":
builder.Register("complain")
builder.Unregister("enforce")
case "enforce":
builder.Unregister("complain")
}
}

View File

@ -8,10 +8,12 @@ package directive
import ( import (
"fmt" "fmt"
"path/filepath"
"slices" "slices"
"strings" "strings"
"github.com/roddhjav/apparmor.d/pkg/aa" "github.com/roddhjav/apparmor.d/pkg/aa"
"github.com/roddhjav/apparmor.d/pkg/paths"
"github.com/roddhjav/apparmor.d/pkg/prebuild" "github.com/roddhjav/apparmor.d/pkg/prebuild"
) )
@ -43,7 +45,14 @@ func (d Exec) Apply(opt *Option, profileRaw string) (string, error) {
rules := aa.Rules{} rules := aa.Rules{}
for name := range opt.ArgMap { for name := range opt.ArgMap {
profiletoTransition := prebuild.RootApparmord.Join(name).MustReadFileAsString() match, err := filepath.Glob(prebuild.Root.String() + "/*/" + name)
if err != nil {
return "", err
}
if len(match) != 1 {
return "", fmt.Errorf("No profile found for %s", name)
}
profiletoTransition := paths.New(match[0]).MustReadFileAsString()
dstProfile := aa.DefaultTunables() dstProfile := aa.DefaultTunables()
if _, err := dstProfile.Parse(profiletoTransition); err != nil { if _, err := dstProfile.Parse(profiletoTransition); err != nil {
return "", err return "", err

View File

@ -6,10 +6,12 @@ package directive
import ( import (
"fmt" "fmt"
"path/filepath"
"regexp" "regexp"
"slices" "slices"
"strings" "strings"
"github.com/roddhjav/apparmor.d/pkg/paths"
"github.com/roddhjav/apparmor.d/pkg/prebuild" "github.com/roddhjav/apparmor.d/pkg/prebuild"
"github.com/roddhjav/apparmor.d/pkg/util" "github.com/roddhjav/apparmor.d/pkg/util"
) )
@ -55,7 +57,14 @@ func (s Stack) Apply(opt *Option, profile string) (string, error) {
res := "" res := ""
for name := range opt.ArgMap { for name := range opt.ArgMap {
stackedProfile := prebuild.RootApparmord.Join(name).MustReadFileAsString() match, err := filepath.Glob(prebuild.Root.String() + "/*/" + name)
if err != nil {
return "", err
}
if len(match) != 1 {
return "", fmt.Errorf("No profile found for %s", name)
}
stackedProfile := paths.New(match[0]).MustReadFileAsString()
m := regRules.FindStringSubmatch(stackedProfile) m := regRules.FindStringSubmatch(stackedProfile)
if len(m) < 2 { if len(m) < 2 {
return "", fmt.Errorf("No profile found in %s", name) return "", fmt.Errorf("No profile found in %s", name)

View File

@ -4,17 +4,28 @@
package prebuild package prebuild
import "github.com/roddhjav/apparmor.d/pkg/paths" import (
"os"
"strings"
"github.com/roddhjav/apparmor.d/pkg/paths"
)
var ( var (
// AppArmor ABI version // AppArmor ABI version
ABI uint = 0 ABI uint = 0
// Root is the root directory for the build (default: .build) // Root is the root directory for the build (default: ./.build)
Root *paths.Path = paths.New(".build") Root *paths.Path = getRootBuild()
// RootApparmord is the final built apparmor.d directory (default: .build/apparmor.d) // RootApparmord is the final built apparmor.d directory (default: .build/apparmor.d)
RootApparmord *paths.Path = Root.Join("apparmor.d") RootApparmord *paths.Path = Root.Join(Src)
// src is the basename of the source directory (default: apparmor.d)
Src = "apparmor.d"
// SrcApparmord is the source apparmor.d directory (default: ./apparmor.d)
SrcApparmord *paths.Path = paths.New(Src)
// DistDir is the directory where the distribution specific files are stored // DistDir is the directory where the distribution specific files are stored
DistDir *paths.Path = paths.New("dists") DistDir *paths.Path = paths.New("dists")
@ -25,6 +36,9 @@ var (
// IgnoreDir is the directory where the ignore files are stored // IgnoreDir is the directory where the ignore files are stored
IgnoreDir *paths.Path = DistDir.Join("ignore") IgnoreDir *paths.Path = DistDir.Join("ignore")
// PkgDir is the directory where the packages files are stored
PkgDir *paths.Path = DistDir.Join("packages")
// SystemdDir is the directory where the systemd drop-in files are stored // SystemdDir is the directory where the systemd drop-in files are stored
SystemdDir *paths.Path = paths.New("systemd") SystemdDir *paths.Path = paths.New("systemd")
@ -34,6 +48,29 @@ var (
// DebianHide is the path to the debian/apparmor.d.hide file // DebianHide is the path to the debian/apparmor.d.hide file
DebianHide = DebianHider{path: DebianDir.Join("apparmor.d.hide")} DebianHide = DebianHider{path: DebianDir.Join("apparmor.d.hide")}
// Packages are the packages to build
Packages = getPackages()
Ignore = Ignorer{} Ignore = Ignorer{}
Flags = Flagger{} Flags = Flagger{}
) )
func getRootBuild() *paths.Path {
root, present := os.LookupEnv("BUILD")
if !present {
root = ".build"
}
return paths.New(root)
}
func getPackages() []string {
files, err := PkgDir.ReadDirRecursiveFiltered(nil, paths.FilterOutDirectories())
if err != nil {
return []string{}
}
packages := make([]string, 0, len(files))
for _, file := range files {
packages = append(packages, strings.TrimSuffix(file.Base(), ".conf"))
}
return packages
}

231
pkg/prebuild/packages.go Normal file
View File

@ -0,0 +1,231 @@
// apparmor.d - Full set of apparmor profiles
// Copyright (C) 2021-2024 Alexandre Pujol <alexandre@pujol.io>
// SPDX-License-Identifier: GPL-2.0-only
package prebuild
import (
"fmt"
"slices"
"strings"
"github.com/roddhjav/apparmor.d/pkg/paths"
)
type Package struct {
Name string
Mode string
Required []string
Profiles []string
Ignores []string
Ignored []string
builddir *paths.Path
}
func NewPackage(name string) *Package {
path := PkgDir.Join(name + ".conf")
if !path.Exist() {
panic(fmt.Sprintf("Unknown package: %s", name))
}
lines := path.MustReadFilteredFileAsLines()
mode := ""
profiles := make([]string, 0, len(lines))
ignores := []string{}
dependencies := []string{}
ignored := getFilesIgnoredByDistribution()
for _, line := range lines {
switch {
case strings.HasPrefix(line, "mode="):
mode = strings.TrimPrefix(line, "mode=")
case strings.HasPrefix(line, "require="):
dependencies = strings.Split(strings.TrimPrefix(line, "require="), ",")
case strings.HasPrefix(line, "!"):
ignores = append(ignores, strings.TrimPrefix(line, "!"))
default:
profiles = append(profiles, line)
}
}
return &Package{
Name: name,
Mode: mode,
Required: dependencies,
Profiles: profiles,
Ignores: ignores,
Ignored: ignored,
builddir: Root.Join(name),
}
}
func getFilesIgnoredByDistribution() []string {
res := []string{}
for _, iname := range []string{"main", Distribution} {
for _, ignore := range Ignore.Read(iname) {
if !strings.HasPrefix(ignore, Src) {
continue
}
profile := strings.TrimPrefix(ignore, Src+"/")
path := SrcApparmord.Join(profile)
if path.IsDir() {
files, err := path.ReadDirRecursiveFiltered(nil, paths.FilterOutDirectories())
if err != nil {
panic(err)
}
for _, file := range files {
res = append(res, file.Base())
}
} else if path.Exist() {
res = append(res, path.Base())
} else {
panic(fmt.Errorf("%s.ignore: no files found for '%s'", iname, profile))
}
}
}
return res
}
func (p *Package) Generate() ([]string, error) {
var res []string
if err := p.builddir.RemoveAll(); err != nil {
return res, err
}
if err := p.builddir.MkdirAll(); err != nil {
return res, err
}
explode := paths.PathList{
paths.New("groups"), paths.New("profiles-a-f"),
paths.New("profiles-m-r"), paths.New("profiles-s-z"),
}
for _, name := range p.Profiles {
originalPath := SrcApparmord.Join(name)
if originalPath.IsDir() {
originFiles, err := originalPath.ReadDirRecursiveFiltered(nil, paths.FilterOutDirectories())
if err != nil {
return res, err
}
for _, originFile := range originFiles {
file, err := originFile.RelFrom(SrcApparmord)
if err != nil {
return res, err
}
if slices.Contains(p.Ignores, file.String()) {
continue
}
done := false
for _, e := range explode {
if ok, _ := file.IsInsideDir(e); ok {
base := file.Base()
msg, err := p.move(base)
if err != nil {
return res, err
}
res = append(res, msg)
done = true
break
}
}
if !done {
msg, err := p.move(file)
if err != nil {
return res, err
}
res = append(res, msg)
}
}
} else if originalPath.Exist() {
base := originalPath.Base()
if slices.Contains(p.Ignores, base) {
continue
}
msg, err := p.move(base)
if err != nil {
return res, err
}
res = append(res, msg)
} else {
return res, fmt.Errorf("No %s", originalPath)
}
}
return res, nil
}
func (p *Package) move(origin any) (string, error) {
var src *paths.Path
var dst *paths.Path
var srcOverridden *paths.Path
var dstOverridden *paths.Path
var srcSymlink *paths.Path
var dstSymlink *paths.Path
const ext = ".apparmor.d"
switch value := any(origin).(type) {
case string:
src = RootApparmord.Join(value)
dst = p.builddir.Join(value)
srcOverridden = RootApparmord.Join(value + ext)
dstOverridden = p.builddir.Join(value + ext)
srcSymlink = RootApparmord.Join("disable", value)
dstSymlink = p.builddir.Join("disable", value)
case *paths.Path:
src = RootApparmord.JoinPath(value)
dst = p.builddir.JoinPath(value)
srcOverridden = RootApparmord.JoinPath(value.Parent()).Join(value.Base() + ext)
dstOverridden = p.builddir.JoinPath(value.Parent()).Join(value.Base() + ext)
srcSymlink = RootApparmord.Join("disable").JoinPath(value)
dstSymlink = p.builddir.Join("disable").JoinPath(value)
default:
panic("Package.move: unsupported type")
}
if src.Exist() {
if err := dst.Parent().MkdirAll(); err != nil {
return "", nil
}
if err := src.Rename(dst); err != nil {
return "", nil
}
// fmt.Printf("%s -> %s\n", src, dst)
} else if srcOverridden.Exist() {
if err := dstOverridden.Parent().MkdirAll(); err != nil {
return "", nil
}
if err := dstSymlink.Parent().MkdirAll(); err != nil {
return "", nil
}
if err := srcOverridden.Rename(dstOverridden); err != nil {
return "", nil
}
if err := srcSymlink.Rename(dstSymlink); err != nil {
return "", nil
}
// fmt.Printf("%s -> %s\n", srcOverridden, dstOverridden)
} else {
srcRltv, err := src.RelFrom(RootApparmord)
if err != nil {
return "", nil
}
if !slices.Contains(p.Ignored, srcRltv.String()) {
fmt.Printf("Warning: No %s\n", src)
// return "", fmt.Errorf("No %s", src)
}
}
return "", nil
}
// Validate ensures a package has its required dependencies
func (p *Package) Validate() error {
return nil
}

View File

@ -5,6 +5,9 @@
package prepare package prepare
import ( import (
"fmt"
"strings"
"github.com/roddhjav/apparmor.d/pkg/paths" "github.com/roddhjav/apparmor.d/pkg/paths"
"github.com/roddhjav/apparmor.d/pkg/prebuild" "github.com/roddhjav/apparmor.d/pkg/prebuild"
) )
@ -26,21 +29,39 @@ func (p Ignore) Apply() ([]string, error) {
res := []string{} res := []string{}
for _, name := range []string{"main", prebuild.Distribution} { for _, name := range []string{"main", prebuild.Distribution} {
for _, ignore := range prebuild.Ignore.Read(name) { for _, ignore := range prebuild.Ignore.Read(name) {
profile := prebuild.Root.Join(ignore) // Ignore file from share/
if profile.NotExist() { path := prebuild.Root.Join(ignore)
files, err := prebuild.RootApparmord.ReadDirRecursiveFiltered(nil, paths.FilterNames(ignore)) if path.Exist() {
if err := path.RemoveAll(); err != nil {
return res, err
}
continue
}
// Ignore file from apparmor.d/
profile := strings.TrimPrefix(ignore, prebuild.Src+"/")
if strings.HasPrefix(ignore, prebuild.Src) {
path = prebuild.RootApparmord.Join(profile)
}
if path.Exist() {
if err := path.RemoveAll(); err != nil {
return res, err
}
} else {
files, err := prebuild.RootApparmord.ReadDirRecursiveFiltered(nil, paths.FilterNames(profile))
if err != nil { if err != nil {
return res, err return res, err
} }
if len(files) == 0 {
return res, fmt.Errorf("%s.ignore: no files found for '%s'", name, profile)
}
for _, path := range files { for _, path := range files {
if err := path.RemoveAll(); err != nil { if err := path.RemoveAll(); err != nil {
return res, err return res, err
} }
} }
} else {
if err := profile.RemoveAll(); err != nil {
return res, err
}
} }
} }
res = append(res, prebuild.IgnoreDir.Join(name+".ignore").String()) res = append(res, prebuild.IgnoreDir.Join(name+".ignore").String())

View File

@ -48,7 +48,7 @@ func (p Merge) Apply() ([]string, error) {
files, err = filepath.Glob(prebuild.RootApparmord.Join(dirRemoved).String()) files, err = filepath.Glob(prebuild.RootApparmord.Join(dirRemoved).String())
if err != nil { if err != nil {
return []string{}, err return res, err
} }
for _, file := range files { for _, file := range files {
if err := paths.New(file).RemoveAll(); err != nil { if err := paths.New(file).RemoveAll(); err != nil {

View File

@ -50,7 +50,6 @@ func (p Overwrite) Apply() ([]string, error) {
continue continue
} }
if err := origin.Rename(dest); err != nil { if err := origin.Rename(dest); err != nil {
return res, err return res, err
} }
originRel, err := origin.RelFrom(dest) originRel, err := origin.RelFrom(dest)

View File

@ -33,14 +33,15 @@ func (p Synchronise) Apply() ([]string, error) {
} }
} }
if p.Path == "" { if p.Path == "" {
for _, name := range []string{"apparmor.d", "share"} { if err := paths.CopyTo(paths.New("share"), prebuild.Root.Join("share")); err != nil {
if err := paths.CopyTo(paths.New(name), prebuild.Root.Join(name)); err != nil {
return res, err return res, err
} }
if err := paths.CopyTo(prebuild.SrcApparmord, prebuild.RootApparmord); err != nil {
return res, err
} }
} else { } else {
file := paths.New(p.Path) file := paths.New(p.Path)
destination, err := file.RelFrom(paths.New("apparmor.d")) destination, err := file.RelFrom(prebuild.SrcApparmord)
if err != nil { if err != nil {
return res, err return res, err
} }