2024-03-21 21:36:41 +01:00
|
|
|
// apparmor.d - Full set of apparmor profiles
|
|
|
|
// Copyright (C) 2021-2024 Alexandre Pujol <alexandre@pujol.io>
|
|
|
|
// SPDX-License-Identifier: GPL-2.0-only
|
|
|
|
|
|
|
|
package directive
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/arduino/go-paths-helper"
|
2024-03-25 23:40:25 +01:00
|
|
|
"github.com/roddhjav/apparmor.d/pkg/prebuild/cfg"
|
2024-03-21 21:36:41 +01:00
|
|
|
)
|
|
|
|
|
2024-03-25 23:40:25 +01:00
|
|
|
var (
|
2024-04-02 18:48:03 +02:00
|
|
|
// Define the directive keyword globally
|
|
|
|
Keyword = "#aa:"
|
|
|
|
|
2024-03-25 23:40:25 +01:00
|
|
|
// Build the profiles with the following directive applied
|
|
|
|
Directives = map[string]Directive{}
|
2024-03-21 21:36:41 +01:00
|
|
|
|
2024-03-25 23:40:25 +01:00
|
|
|
regDirective = regexp.MustCompile(`(?m).*` + Keyword + `([a-z]*) (.*)`)
|
|
|
|
)
|
2024-03-21 21:36:41 +01:00
|
|
|
|
|
|
|
// Main directive interface
|
|
|
|
type Directive interface {
|
2024-03-25 23:40:25 +01:00
|
|
|
cfg.BaseInterface
|
2024-03-21 21:36:41 +01:00
|
|
|
Apply(opt *Option, profile string) string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Directive options
|
|
|
|
type Option struct {
|
2024-03-23 18:41:10 +01:00
|
|
|
Name string
|
|
|
|
ArgMap map[string]string
|
|
|
|
ArgList []string
|
|
|
|
File *paths.Path
|
|
|
|
Raw string
|
2024-03-21 21:36:41 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewOption(file *paths.Path, match []string) *Option {
|
|
|
|
if len(match) != 3 {
|
|
|
|
panic(fmt.Sprintf("Invalid directive: %v", match))
|
|
|
|
}
|
2024-03-23 18:41:10 +01:00
|
|
|
argList := strings.Fields(match[2])
|
|
|
|
argMap := map[string]string{}
|
|
|
|
for _, t := range argList {
|
2024-03-21 21:36:41 +01:00
|
|
|
tmp := strings.Split(t, "=")
|
|
|
|
if len(tmp) < 2 {
|
2024-03-23 18:41:10 +01:00
|
|
|
argMap[tmp[0]] = ""
|
2024-03-21 21:36:41 +01:00
|
|
|
} else {
|
2024-03-23 18:41:10 +01:00
|
|
|
argMap[tmp[0]] = tmp[1]
|
2024-03-21 21:36:41 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return &Option{
|
2024-03-23 18:41:10 +01:00
|
|
|
Name: match[1],
|
|
|
|
ArgMap: argMap,
|
|
|
|
ArgList: argList,
|
|
|
|
File: file,
|
|
|
|
Raw: match[0],
|
2024-03-21 21:36:41 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-25 23:40:25 +01:00
|
|
|
func RegisterDirective(d Directive) {
|
|
|
|
Directives[d.Name()] = d
|
|
|
|
}
|
|
|
|
|
2024-03-21 21:36:41 +01:00
|
|
|
func Run(file *paths.Path, profile string) string {
|
|
|
|
for _, match := range regDirective.FindAllStringSubmatch(profile, -1) {
|
|
|
|
opt := NewOption(file, match)
|
|
|
|
drtv, ok := Directives[opt.Name]
|
|
|
|
if !ok {
|
|
|
|
panic(fmt.Sprintf("Unknown directive: %s", opt.Name))
|
|
|
|
}
|
|
|
|
profile = drtv.Apply(opt, profile)
|
|
|
|
}
|
|
|
|
return profile
|
|
|
|
}
|