feat(prebuild): make prebuild available as an external package.

Usefull for downstream repo.
This commit is contained in:
Alexandre Pujol 2023-05-06 13:01:07 +01:00
parent 538da05696
commit 913ac3131c
No known key found for this signature in database
GPG key ID: C5469996F0DF68EC
13 changed files with 304 additions and 214 deletions

View file

@ -1,66 +0,0 @@
// apparmor.d - Full set of apparmor profiles
// Copyright (C) 2023 Alexandre Pujol <alexandre@pujol.io>
// SPDX-License-Identifier: GPL-2.0-only
package main
import (
"regexp"
"strings"
"github.com/roddhjav/apparmor.d/pkg/aa"
"github.com/roddhjav/apparmor.d/pkg/util"
)
var (
regABI = regexp.MustCompile(`abi <abi/[0-9.]*>,\n`)
regAttachments = regexp.MustCompile(`(profile .* @{exec_path})`)
regFlag = regexp.MustCompile(`flags=\(([^)]+)\)`)
regProfileHeader = regexp.MustCompile(` {`)
)
// Set complain flag on all profiles
func BuildComplain(profile string) string {
if !Complain {
return profile
}
flags := []string{}
matches := regFlag.FindStringSubmatch(profile)
if len(matches) != 0 {
flags = strings.Split(matches[1], ",")
if util.InSlice("complain", flags) {
return profile
}
}
flags = append(flags, "complain")
strFlags := " flags=(" + strings.Join(flags, ",") + ") {"
// Remove all flags definition, then set manifest' flags
profile = regFlag.ReplaceAllLiteralString(profile, "")
return regProfileHeader.ReplaceAllLiteralString(profile, strFlags)
}
// Bypass userspace tools restriction
func BuildUserspace(profile string) string {
p := aa.NewAppArmorProfile(profile)
p.ParseVariables()
p.ResolveAttachments()
att := p.NestAttachments()
matches := regAttachments.FindAllString(profile, -1)
if len(matches) > 0 {
strheader := strings.Replace(matches[0], "@{exec_path}", att, -1)
return regAttachments.ReplaceAllLiteralString(profile, strheader)
}
return profile
}
// Remove abi header for distributions that don't support it
func BuildABI(profile string) string {
switch Distribution {
case "debian", "whonix":
return regABI.ReplaceAllLiteralString(profile, "")
default:
return profile
}
}

View file

@ -9,9 +9,9 @@ import (
"fmt"
"os"
"github.com/arduino/go-paths-helper"
"github.com/roddhjav/apparmor.d/pkg/logging"
"github.com/roddhjav/apparmor.d/pkg/util"
"github.com/roddhjav/apparmor.d/pkg/prebuild"
"golang.org/x/exp/slices"
)
const usage = `prebuild [-h] [--full] [--complain]
@ -20,82 +20,53 @@ const usage = `prebuild [-h] [--full] [--complain]
Options:
-h, --help Show this help message and exit.
-d, --dist The target Linux distribution.
-f, --full Set AppArmor for full system policy.
-c, --complain Set complain flag on all profiles.
`
var (
help bool
Full bool
Complain bool
Distribution string
DistDir *paths.Path
Root *paths.Path
RootApparmord *paths.Path
// Prepare the build directory with the following tasks
prepare = []prepareFunc{Synchronise, Ignore, Merge, Configure, SetFlags, SetFullSystemPolicy}
// Build the profiles with the following build tasks
build = []buildFunc{BuildUserspace, BuildComplain, BuildABI}
help bool
full bool
complain bool
)
type prepareFunc func() error
type buildFunc func(string) string
func init() {
DistDir = paths.New("dists")
Root = paths.New(".build")
RootApparmord = Root.Join("apparmor.d")
Distribution, _ = util.GetSupportedDistribution()
flag.BoolVar(&help, "h", false, "Show this help message and exit.")
flag.BoolVar(&help, "help", false, "Show this help message and exit.")
flag.BoolVar(&Full, "f", false, "Set AppArmor for full system policy.")
flag.BoolVar(&Full, "full", false, "Set AppArmor for full system policy.")
flag.BoolVar(&Complain, "c", false, "Set complain flag on all profiles.")
flag.BoolVar(&Complain, "complain", false, "Set complain flag on all profiles.")
}
// Build the profiles.
func buildProfiles() error {
files, _ := RootApparmord.ReadDir(paths.FilterOutDirectories())
for _, file := range files {
if !file.Exist() {
continue
}
content, _ := file.ReadFile()
profile := string(content)
for _, fct := range build {
profile = fct(profile)
}
if err := file.WriteFile([]byte(profile)); err != nil {
panic(err)
}
}
return nil
flag.BoolVar(&full, "f", false, "Set AppArmor for full system policy.")
flag.BoolVar(&full, "full", false, "Set AppArmor for full system policy.")
flag.BoolVar(&complain, "c", false, "Set complain flag on all profiles.")
flag.BoolVar(&complain, "complain", false, "Set complain flag on all profiles.")
}
func aaPrebuild() error {
logging.Step("Building apparmor.d profiles for %s.", Distribution)
logging.Step("Building apparmor.d profiles for %s.", prebuild.Distribution)
for _, fct := range prepare {
if err := fct(); err != nil {
return err
}
if full {
prebuild.Prepares = append(prebuild.Prepares, prebuild.SetFullSystemPolicy)
}
if complain {
prebuild.Builds = append(prebuild.Builds, prebuild.BuildComplain)
}
if slices.Contains([]string{"debian", "whonix"}, prebuild.Distribution) {
prebuild.Builds = append(prebuild.Builds, prebuild.BuildABI)
}
if err := buildProfiles(); err != nil {
if err := prebuild.Prepare(); err != nil {
return err
}
if err := prebuild.Build(); err != nil {
return err
}
logging.Success("Builded profiles with: ")
logging.Bullet("Bypass userspace tools restriction")
if Complain {
if complain {
logging.Bullet("Set complain flag on all profiles")
}
switch Distribution {
case "debian", "whonix":
logging.Bullet("%s does not support abi 3.0 yet", Distribution)
if slices.Contains([]string{"debian", "whonix"}, prebuild.Distribution) {
logging.Bullet("%s does not support abi 3.0 yet", prebuild.Distribution)
}
return nil
}
@ -107,8 +78,7 @@ func main() {
flag.Usage()
os.Exit(0)
}
err := aaPrebuild()
if err != nil {
if err := aaPrebuild(); err != nil {
logging.Fatal(err.Error())
}
}

View file

@ -8,6 +8,8 @@ import (
"os"
"os/exec"
"testing"
"github.com/roddhjav/apparmor.d/pkg/prebuild"
)
func chdirGitRoot() {
@ -22,7 +24,7 @@ func chdirGitRoot() {
}
}
func Test_aaPrebuild(t *testing.T) {
func Test_AAPrebuild(t *testing.T) {
tests := []struct {
name string
wantErr bool
@ -58,20 +60,24 @@ func Test_aaPrebuild(t *testing.T) {
complain: true,
dist: "opensuse",
},
{
name: "Build for Fedora",
wantErr: true,
full: false,
complain: false,
dist: "fedora",
},
// {
// name: "Build for Fedora",
// wantErr: true,
// full: false,
// complain: false,
// dist: "fedora",
// },
}
chdirGitRoot()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Distribution = tt.dist
Complain = tt.complain
Full = tt.full
prebuild.Distribution = tt.dist
if tt.full {
prebuild.Prepares = append(prebuild.Prepares, prebuild.SetFullSystemPolicy)
}
if tt.complain {
prebuild.Builds = append(prebuild.Builds, prebuild.BuildComplain)
}
if err := aaPrebuild(); (err != nil) != tt.wantErr {
t.Errorf("aaPrebuild() error = %v, wantErr %v", err, tt.wantErr)
}

View file

@ -1,243 +0,0 @@
// apparmor.d - Full set of apparmor profiles
// Copyright (C) 2023 Alexandre Pujol <alexandre@pujol.io>
// SPDX-License-Identifier: GPL-2.0-only
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/arduino/go-paths-helper"
"github.com/roddhjav/apparmor.d/pkg/aa"
"github.com/roddhjav/apparmor.d/pkg/logging"
)
// Initialize a new clean apparmor.d build directory
func Synchronise() error {
dirs := paths.PathList{RootApparmord, Root.Join("root")}
for _, dir := range dirs {
if err := dir.RemoveAll(); err != nil {
return err
}
}
for _, path := range []string{"./apparmor.d", "./root"} {
cmd := exec.Command("rsync", "-a", path, Root.String())
if err := cmd.Run(); err != nil {
return err
}
}
logging.Success("Initialize a new clean apparmor.d build directory")
return nil
}
// Ignore profiles and files as defined in dists/ignore/
func Ignore() error {
for _, name := range []string{"main.ignore", Distribution + ".ignore"} {
path := DistDir.Join("ignore", name)
if !path.Exist() {
continue
}
lines, _ := path.ReadFileAsLines()
for _, line := range lines {
if strings.HasPrefix(line, "#") || line == "" {
continue
}
profile := Root.Join(line)
if profile.NotExist() {
files, err := RootApparmord.ReadDirRecursiveFiltered(nil, paths.FilterNames(line))
if err != nil {
return err
}
for _, path := range files {
if err := path.RemoveAll(); err != nil {
return err
}
}
} else {
if err := profile.RemoveAll(); err != nil {
return err
}
}
}
logging.Success("Ignore profiles/files in %s", path)
}
return nil
}
// Merge all profiles in a new apparmor.d directory
func Merge() error {
var dirToMerge = []string{
"groups/*/*", "groups",
"profiles-*-*/*", "profiles-*",
}
idx := 0
for idx < len(dirToMerge)-1 {
dirMoved, dirRemoved := dirToMerge[idx], dirToMerge[idx+1]
files, err := filepath.Glob(RootApparmord.Join(dirMoved).String())
if err != nil {
return err
}
for _, file := range files {
err := os.Rename(file, RootApparmord.Join(filepath.Base(file)).String())
if err != nil {
return err
}
}
files, err = filepath.Glob(RootApparmord.Join(dirRemoved).String())
if err != nil {
return err
}
for _, file := range files {
if err := paths.New(file).RemoveAll(); err != nil {
return err
}
}
idx = idx + 2
}
logging.Success("Merge all profiles")
return nil
}
// Set the distribution specificities
func Configure() error {
switch Distribution {
case "arch":
if err := setLibexec("/{usr/,}lib"); err != nil {
return err
}
case "opensuse":
if err := setLibexec("/{usr/,}libexec"); err != nil {
return err
}
case "debian", "ubuntu", "whonix":
if err := setLibexec("/{usr/,}libexec"); err != nil {
return err
}
// Copy Ubuntu specific profiles
if err := copyTo(DistDir.Join("ubuntu"), RootApparmord); err != nil {
return err
}
if Distribution == "ubuntu" {
break
}
// Copy debian specific profiles
if err := copyTo(DistDir.Join("debian"), RootApparmord); err != nil {
return err
}
// Remove ABI on abstractions files
files, _ := RootApparmord.Join("abstractions").ReadDir(paths.FilterOutDirectories())
for _, file := range files {
if !file.Exist() {
continue
}
content, _ := file.ReadFile()
profile := BuildABI(string(content))
if err := file.WriteFile([]byte(profile)); err != nil {
return err
}
}
default:
return fmt.Errorf("%s is not a supported distribution", Distribution)
}
return nil
}
func setLibexec(libexec string) error {
aa.Tunables["libexec"] = []string{libexec}
file, err := RootApparmord.Join("tunables", "multiarch.d", "apparmor.d").Append()
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(`@{libexec}=` + libexec)
return err
}
func copyTo(src *paths.Path, dst *paths.Path) error {
files, err := src.ReadDirRecursiveFiltered(nil, paths.FilterOutDirectories())
if err != nil {
return err
}
for _, file := range files {
destination, err := file.RelFrom(src)
if err != nil {
return err
}
destination = dst.JoinPath(destination)
if err := file.CopyTo(destination); err != nil {
return err
}
}
return nil
}
// Set flags on some profiles according to manifest defined in `dists/flags/`
func SetFlags() error {
for _, name := range []string{"main.flags", Distribution + ".flags"} {
path := DistDir.Join("flags", name)
if !path.Exist() {
continue
}
lines, _ := path.ReadFileAsLines()
for _, line := range lines {
if strings.HasPrefix(line, "#") || line == "" {
continue
}
manifest := strings.Split(line, " ")
profile := manifest[0]
file := RootApparmord.Join(profile)
if !file.Exist() {
logging.Warning("Profile %s not found", profile)
continue
}
// If flags is set, overwrite profile flag
if len(manifest) > 1 {
flags := " flags=(" + manifest[1] + ") {"
content, err := file.ReadFile()
if err != nil {
return err
}
// Remove all flags definition, then set manifest' flags
res := regFlag.ReplaceAllLiteralString(string(content), "")
res = regProfileHeader.ReplaceAllLiteralString(res, flags)
if err := file.WriteFile([]byte(res)); err != nil {
return err
}
}
}
logging.Success("Set profile flags from %s", path)
}
return nil
}
// Set AppArmor for full system policy
// See https://gitlab.com/apparmor/apparmor/-/wikis/FullSystemPolicy
// https://gitlab.com/apparmor/apparmor/-/wikis/AppArmorInSystemd#early-policy-loads
func SetFullSystemPolicy() error {
if !Full {
return nil
}
for _, name := range []string{"init", "systemd"} {
err := paths.New("apparmor.d/groups/_full/" + name).CopyTo(RootApparmord.Join(name))
if err != nil {
return err
}
}
logging.Success("Configure AppArmor for full system policy")
return nil
}