chore: apply some linter recommendations.

This commit is contained in:
Alexandre Pujol 2025-04-04 23:45:24 +02:00
parent 3b6b50cf63
commit 984cf28e61
No known key found for this signature in database
GPG key ID: C5469996F0DF68EC
37 changed files with 125 additions and 126 deletions

View file

@ -55,7 +55,7 @@ func aaLog(logger string, path string, profile string) error {
case "systemd": case "systemd":
file, err = logs.GetJournalctlLogs(path, since, !slices.Contains(logs.LogFiles, path)) file, err = logs.GetJournalctlLogs(path, since, !slices.Contains(logs.LogFiles, path))
default: default:
err = fmt.Errorf("Logger %s not supported.", logger) err = fmt.Errorf("logger %s not supported", logger)
} }
if err != nil { if err != nil {
return err return err

View file

@ -8,7 +8,7 @@ import (
"github.com/roddhjav/apparmor.d/pkg/paths" "github.com/roddhjav/apparmor.d/pkg/paths"
) )
// Default Apparmor magic directory: /etc/apparmor.d/. // MagicRoot is the default Apparmor magic directory: /etc/apparmor.d/.
var MagicRoot = paths.New("/etc/apparmor.d") var MagicRoot = paths.New("/etc/apparmor.d")
// AppArmorProfileFiles represents a full set of apparmor profiles // AppArmorProfileFiles represents a full set of apparmor profiles

View file

@ -104,10 +104,7 @@ type Qualifier struct {
} }
func newQualifierFromLog(log map[string]string) Qualifier { func newQualifierFromLog(log map[string]string) Qualifier {
audit := false audit := log["apparmor"] == "AUDIT"
if log["apparmor"] == "AUDIT" {
audit = true
}
return Qualifier{Audit: audit} return Qualifier{Audit: audit}
} }

View file

@ -27,21 +27,21 @@ func (p *Hat) String() string {
return renderTemplate(p.Kind(), p) return renderTemplate(p.Kind(), p)
} }
func (r *Hat) Validate() error { func (p *Hat) Validate() error {
return nil return nil
} }
func (r *Hat) Compare(other Rule) int { func (p *Hat) Compare(other Rule) int {
o, _ := other.(*Hat) o, _ := other.(*Hat)
return compare(r.Name, o.Name) return compare(p.Name, o.Name)
} }
func (r *Hat) Merge(other Rule) bool { func (p *Hat) Merge(other Rule) bool {
return false // Never merge hat blocks return false // Never merge hat blocks
} }
func (r *Hat) Lengths() []int { func (p *Hat) Lengths() []int {
return []int{} // No len for hat return []int{} // No len for hat
} }
func (r *Hat) setPaddings(max []int) {} // No paddings for hat func (p *Hat) setPaddings(max []int) {} // No paddings for hat

View file

@ -84,8 +84,8 @@ func (r *Capability) Merge(other Rule) bool {
func (r *Capability) Lengths() []int { func (r *Capability) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.Names), length("", r.Names),
} }
} }

View file

@ -106,8 +106,8 @@ func (r *ChangeProfile) Merge(other Rule) bool {
func (r *ChangeProfile) Lengths() []int { func (r *ChangeProfile) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.ExecMode), length("", r.ExecMode),
length("", r.Exec), length("", r.Exec),
length("", r.ProfileName), length("", r.ProfileName),

View file

@ -125,7 +125,7 @@ func (r *Dbus) Compare(other Rule) int {
func (r *Dbus) Merge(other Rule) bool { func (r *Dbus) Merge(other Rule) bool {
o, _ := other.(*Dbus) o, _ := other.(*Dbus)
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.Bus == o.Bus && r.Name == o.Name && r.Path == o.Path && if r.Bus == o.Bus && r.Name == o.Name && r.Path == o.Path &&

View file

@ -168,7 +168,7 @@ func (r *File) Compare(other Rule) int {
func (r *File) Merge(other Rule) bool { func (r *File) Merge(other Rule) bool {
o, _ := other.(*File) o, _ := other.(*File)
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.Owner == o.Owner && r.Path == o.Path && r.Target == o.Target { if r.Owner == o.Owner && r.Path == o.Path && r.Target == o.Target {
@ -189,8 +189,8 @@ func (r *File) Lengths() []int {
lenPath = length("", r.Path) lenPath = length("", r.Path)
} }
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("owner", r.Owner), length("owner", r.Owner),
lenPath, lenPath,
} }
@ -314,8 +314,8 @@ func (r *Link) Merge(other Rule) bool {
func (r *Link) Lengths() []int { func (r *Link) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("owner", r.Owner), length("owner", r.Owner),
length("subset", r.Subset), length("subset", r.Subset),
length("", r.Path), length("", r.Path),

View file

@ -78,7 +78,7 @@ func (r *IOUring) Compare(other Rule) int {
func (r *IOUring) Merge(other Rule) bool { func (r *IOUring) Merge(other Rule) bool {
o, _ := other.(*IOUring) o, _ := other.(*IOUring)
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.Label == o.Label { if r.Label == o.Label {
@ -91,8 +91,8 @@ func (r *IOUring) Merge(other Rule) bool {
func (r *IOUring) Lengths() []int { func (r *IOUring) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.Access), length("", r.Access),
length("label=", r.Label), length("label=", r.Label),
} }

View file

@ -181,7 +181,7 @@ func (r *Mount) Merge(other Rule) bool {
o, _ := other.(*Mount) o, _ := other.(*Mount)
mc := &r.MountConditions mc := &r.MountConditions
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.Source == o.Source && r.MountPoint == o.MountPoint && if r.Source == o.Source && r.MountPoint == o.MountPoint &&
@ -194,10 +194,10 @@ func (r *Mount) Merge(other Rule) bool {
func (r *Mount) Lengths() []int { func (r *Mount) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
r.MountConditions.getLenFsType(), r.getLenFsType(),
r.MountConditions.getLenOptions(), r.getLenOptions(),
length("", r.Source), length("", r.Source),
length("", r.MountPoint), length("", r.MountPoint),
} }
@ -278,7 +278,7 @@ func (r *Umount) Merge(other Rule) bool {
o, _ := other.(*Umount) o, _ := other.(*Umount)
mc := &r.MountConditions mc := &r.MountConditions
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.MountPoint == o.MountPoint && mc.Merge(o.MountConditions) { if r.MountPoint == o.MountPoint && mc.Merge(o.MountConditions) {
@ -290,10 +290,10 @@ func (r *Umount) Merge(other Rule) bool {
func (r *Umount) Lengths() []int { func (r *Umount) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
r.MountConditions.getLenFsType(), r.getLenFsType(),
r.MountConditions.getLenOptions(), r.getLenOptions(),
length("", r.MountPoint), length("", r.MountPoint),
} }
} }
@ -374,7 +374,7 @@ func (r *Remount) Merge(other Rule) bool {
o, _ := other.(*Remount) o, _ := other.(*Remount)
mc := &r.MountConditions mc := &r.MountConditions
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.MountPoint == o.MountPoint && mc.Merge(o.MountConditions) { if r.MountPoint == o.MountPoint && mc.Merge(o.MountConditions) {
@ -386,10 +386,10 @@ func (r *Remount) Merge(other Rule) bool {
func (r *Remount) Lengths() []int { func (r *Remount) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
r.MountConditions.getLenFsType(), r.getLenFsType(),
r.MountConditions.getLenOptions(), r.getLenOptions(),
length("", r.MountPoint), length("", r.MountPoint),
} }
} }

View file

@ -112,7 +112,7 @@ func (r *Mqueue) Compare(other Rule) int {
func (r *Mqueue) Merge(other Rule) bool { func (r *Mqueue) Merge(other Rule) bool {
o, _ := other.(*Mqueue) o, _ := other.(*Mqueue)
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.Type == o.Type && r.Label == o.Label && r.Name == o.Name { if r.Type == o.Type && r.Label == o.Label && r.Name == o.Name {
@ -125,8 +125,8 @@ func (r *Mqueue) Merge(other Rule) bool {
func (r *Mqueue) Lengths() []int { func (r *Mqueue) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.Access), length("", r.Access),
length("type=", r.Type), length("type=", r.Type),
length("label=", r.Label), length("label=", r.Label),

View file

@ -147,8 +147,8 @@ func (r *Network) Merge(other Rule) bool {
func (r *Network) Lengths() []int { func (r *Network) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.Domain), length("", r.Domain),
length("", r.Type), length("", r.Type),
length("", r.Protocol), length("", r.Protocol),

View file

@ -514,7 +514,7 @@ func newRules(rules []rule) (Rules, error) {
for _, rule := range rules { for _, rule := range rules {
if len(rule) == 0 { if len(rule) == 0 {
return nil, fmt.Errorf("Empty rule") return nil, fmt.Errorf("empty rule")
} }
owner := false owner := false
@ -563,7 +563,7 @@ func newRules(rules []rule) (Rules, error) {
// return nil, fmt.Errorf("Unknown rule: %s", rule) // return nil, fmt.Errorf("Unknown rule: %s", rule)
} }
} else { } else {
return nil, fmt.Errorf("Unrecognized rule: %s", rule) return nil, fmt.Errorf("unrecognized rule: %s", rule)
} }
} }
} }
@ -657,7 +657,7 @@ done:
return nb, nil return nb, nil
} }
// Parse apparmor profile rules by paragraphs // ParseRules parses apparmor profile rules by paragraphs
func ParseRules(input string) (ParaRules, []string, error) { func ParseRules(input string) (ParaRules, []string, error) {
paragraphRules := ParaRules{} paragraphRules := ParaRules{}
paragraphs := []string{} paragraphs := []string{}

View file

@ -86,8 +86,8 @@ func (r *PivotRoot) Merge(other Rule) bool {
func (r *PivotRoot) Lengths() []int { func (r *PivotRoot) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("oldroot=", r.OldRoot), length("oldroot=", r.OldRoot),
length("", r.NewRoot), length("", r.NewRoot),
length("", r.TargetProfile), length("", r.TargetProfile),

View file

@ -72,10 +72,10 @@ func newAbi(q Qualifier, rule rule) (Rule, error) {
} }
path := rule.Get(0) path := rule.Get(0)
switch { switch path[0] {
case path[0] == '"': case '"':
magic = false magic = false
case path[0] == '<': case '<':
magic = true magic = true
default: default:
return nil, fmt.Errorf("invalid path %s in rule: %s", path, rule) return nil, fmt.Errorf("invalid path %s in rule: %s", path, rule)
@ -198,10 +198,10 @@ func newInclude(rule rule) (Rule, error) {
} }
path := r[0] path := r[0]
switch { switch path[0] {
case path[0] == '"': case '"':
magic = false magic = false
case path[0] == '<': case '<':
magic = true magic = true
default: default:
return nil, fmt.Errorf("invalid path format: %v", path) return nil, fmt.Errorf("invalid path format: %v", path)

View file

@ -81,19 +81,19 @@ func (p *Profile) String() string {
return renderTemplate(p.Kind(), p) return renderTemplate(p.Kind(), p)
} }
func (r *Profile) Validate() error { func (p *Profile) Validate() error {
if err := validateValues(r.Kind(), tokFLAGS, r.Flags); err != nil { if err := validateValues(p.Kind(), tokFLAGS, p.Flags); err != nil {
return fmt.Errorf("profile %s: %w", r.Name, err) return fmt.Errorf("profile %s: %w", p.Name, err)
} }
return r.Rules.Validate() return p.Rules.Validate()
} }
func (r *Profile) Compare(other Rule) int { func (p *Profile) Compare(other Rule) int {
o, _ := other.(*Profile) o, _ := other.(*Profile)
if res := compare(r.Name, o.Name); res != 0 { if res := compare(p.Name, o.Name); res != 0 {
return res return res
} }
return compare(r.Attachments, o.Attachments) return compare(p.Attachments, o.Attachments)
} }
func (p *Profile) Merge(other Rule) bool { func (p *Profile) Merge(other Rule) bool {
@ -103,11 +103,11 @@ func (p *Profile) Merge(other Rule) bool {
return false return false
} }
func (r *Profile) Lengths() []int { func (p *Profile) Lengths() []int {
return []int{} // No len for profile return []int{} // No len for profile
} }
func (r *Profile) setPaddings(max []int) {} // No paddings for profile func (p *Profile) setPaddings(max []int) {} // No paddings for profile
func (p *Profile) Sort() { func (p *Profile) Sort() {
p.Rules = p.Rules.Sort() p.Rules = p.Rules.Sort()

View file

@ -80,7 +80,7 @@ func (r *Ptrace) Compare(other Rule) int {
func (r *Ptrace) Merge(other Rule) bool { func (r *Ptrace) Merge(other Rule) bool {
o, _ := other.(*Ptrace) o, _ := other.(*Ptrace)
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.Peer == o.Peer { if r.Peer == o.Peer {
@ -93,8 +93,8 @@ func (r *Ptrace) Merge(other Rule) bool {
func (r *Ptrace) Lengths() []int { func (r *Ptrace) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.Access), length("", r.Access),
length("peer=", r.Peer), length("peer=", r.Peer),
} }

View file

@ -80,7 +80,7 @@ func (f *AppArmorProfileFile) resolveValues(input string) ([]string, error) {
values := []string{} values := []string{}
match := regVariableReference.FindStringSubmatch(input) match := regVariableReference.FindStringSubmatch(input)
if len(match) == 0 { if len(match) == 0 {
return nil, fmt.Errorf("Invalid variable reference: %s", input) return nil, fmt.Errorf("invalid variable reference: %s", input)
} }
variable := match[0] variable := match[0]
@ -105,7 +105,7 @@ func (f *AppArmorProfileFile) resolveValues(input string) ([]string, error) {
} }
if !found { if !found {
return nil, fmt.Errorf("Variable %s not defined", varname) return nil, fmt.Errorf("variable %s not defined", varname)
} }
return values, nil return values, nil
} }
@ -113,7 +113,7 @@ func (f *AppArmorProfileFile) resolveValues(input string) ([]string, error) {
// resolveInclude resolves all includes defined in the profile preamble // resolveInclude resolves all includes defined in the profile preamble
func (f *AppArmorProfileFile) resolveInclude(include *Include) error { func (f *AppArmorProfileFile) resolveInclude(include *Include) error {
if include == nil || include.Path == "" { if include == nil || include.Path == "" {
return fmt.Errorf("Invalid include: %v", include) return fmt.Errorf("invalid include: %v", include)
} }
_, isCached := includeCache[include] _, isCached := includeCache[include]

View file

@ -106,7 +106,7 @@ func (r *Signal) Compare(other Rule) int {
func (r *Signal) Merge(other Rule) bool { func (r *Signal) Merge(other Rule) bool {
o, _ := other.(*Signal) o, _ := other.(*Signal)
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
switch { switch {
@ -124,8 +124,8 @@ func (r *Signal) Merge(other Rule) bool {
func (r *Signal) Lengths() []int { func (r *Signal) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.Access), length("", r.Access),
length("set=", r.Set), length("set=", r.Set),
length("peer=", r.Peer), length("peer=", r.Peer),

View file

@ -124,7 +124,7 @@ func (r *Unix) Compare(other Rule) int {
func (r *Unix) Merge(other Rule) bool { func (r *Unix) Merge(other Rule) bool {
o, _ := other.(*Unix) o, _ := other.(*Unix)
if !r.Qualifier.Equal(o.Qualifier) { if !r.Equal(o.Qualifier) {
return false return false
} }
if r.Type == o.Type && r.Protocol == o.Protocol && r.Address == o.Address && if r.Type == o.Type && r.Protocol == o.Protocol && r.Address == o.Address &&
@ -139,8 +139,8 @@ func (r *Unix) Merge(other Rule) bool {
func (r *Unix) Lengths() []int { func (r *Unix) Lengths() []int {
return []int{ return []int{
r.Qualifier.getLenAudit(), r.getLenAudit(),
r.Qualifier.getLenAccess(), r.getLenAccess(),
length("", r.Access), length("", r.Access),
length("type=", r.Type), length("type=", r.Type),
length("protocol=", r.Protocol), length("protocol=", r.Protocol),

View file

@ -81,7 +81,7 @@ func Warning(msg string, a ...interface{}) int {
return Print("%s", Warningf(msg, a...)) return Print("%s", Warningf(msg, a...))
} }
// Fatalf returns a formatted error message // Error returns a formatted error message
func Error(msg string, a ...interface{}) int { func Error(msg string, a ...interface{}) int {
return Print("%s", fmt.Sprintf("%s%s%s\n", Indent, errorText, fmt.Sprintf(msg, a...))) return Print("%s", fmt.Sprintf("%s%s%s\n", Indent, errorText, fmt.Sprintf(msg, a...)))
} }

View file

@ -521,7 +521,7 @@ func (p *Path) ReadFileAsLines() ([]string, error) {
return nil, err return nil, err
} }
txt := string(data) txt := string(data)
txt = strings.Replace(txt, "\r\n", "\n", -1) txt = strings.ReplaceAll(txt, "\r\n", "\n")
return strings.Split(txt, "\n"), nil return strings.Split(txt, "\n"), nil
} }
@ -542,7 +542,7 @@ func (p *Path) MustReadFilteredFileAsLines() []string {
panic(err) panic(err)
} }
txt := string(data) txt := string(data)
txt = strings.Replace(txt, "\r\n", "\n", -1) txt = strings.ReplaceAll(txt, "\r\n", "\n")
txt = util.Filter(txt) txt = util.Filter(txt)
res := strings.Split(txt, "\n") res := strings.Split(txt, "\n")
if slices.Contains(res, "") { if slices.Contains(res, "") {
@ -636,7 +636,9 @@ func (p *Path) String() string {
func (p *Path) Canonical() *Path { func (p *Path) Canonical() *Path {
canonical := p.Clone() canonical := p.Clone()
// https://github.com/golang/go/issues/17084#issuecomment-246645354 // https://github.com/golang/go/issues/17084#issuecomment-246645354
canonical.FollowSymLink() if err := canonical.FollowSymLink(); err != nil {
return nil
}
if absPath, err := canonical.Abs(); err == nil { if absPath, err := canonical.Abs(); err == nil {
canonical = absPath canonical = absPath
} }

View file

@ -38,9 +38,9 @@ func (b ReAttach) Apply(opt *Option, profile string) (string, error) {
if strings.Contains(profile, "attach_disconnected") { if strings.Contains(profile, "attach_disconnected") {
insert = "@{att} = /att/" + opt.Name + "/\n" insert = "@{att} = /att/" + opt.Name + "/\n"
profile = strings.Replace(profile, profile = strings.ReplaceAll(profile,
"attach_disconnected", "attach_disconnected",
"attach_disconnected,attach_disconnected.path=@{att}", -1, "attach_disconnected,attach_disconnected.path=@{att}",
) )
old := "include if exists <local/" + opt.Name + ">" old := "include if exists <local/" + opt.Name + ">"

View file

@ -20,13 +20,13 @@ var (
Builders = map[string]Builder{} Builders = map[string]Builder{}
) )
// Main directive interface // Builder main directive interface
type Builder interface { type Builder interface {
prebuild.BaseInterface prebuild.BaseInterface
Apply(opt *Option, profile string) (string, error) Apply(opt *Option, profile string) (string, error)
} }
// Builder options // Option for a builder
type Option struct { type Option struct {
Name string Name string
File *paths.Path File *paths.Path

View file

@ -54,7 +54,7 @@ func (b Userspace) Apply(opt *Option, profile string) (string, error) {
matches := regAttachments.FindAllString(profile, -1) matches := regAttachments.FindAllString(profile, -1)
if len(matches) > 0 { if len(matches) > 0 {
att := f.GetDefaultProfile().GetAttachments() att := f.GetDefaultProfile().GetAttachments()
strheader := strings.Replace(matches[0], tokATTACHMENT, att, -1) strheader := strings.ReplaceAll(matches[0], tokATTACHMENT, att)
return regAttachments.ReplaceAllLiteralString(profile, strheader), nil return regAttachments.ReplaceAllLiteralString(profile, strheader), nil
} }
return profile, nil return profile, nil

View file

@ -18,9 +18,9 @@ import (
) )
const ( const (
nilABI uint = 0 nilABI = 0
nilVer float64 = 0.0 nilVer = 0.0
usage = `aa-prebuild [-h] [--complain | --enforce] [--full] [--abi 3|4] [--version V] [--file FILE] usage = `aa-prebuild [-h] [--complain | --enforce] [--full] [--abi 3|4] [--version V] [--file FILE]
Prebuild apparmor.d profiles for a given distribution and apply Prebuild apparmor.d profiles for a given distribution and apply
internal built-in directives. internal built-in directives.
@ -41,7 +41,7 @@ var (
complain bool complain bool
enforce bool enforce bool
full bool full bool
abi uint abi int
version float64 version float64
file string file string
) )
@ -55,8 +55,8 @@ func init() {
flag.BoolVar(&complain, "complain", false, "Set complain flag on all profiles.") flag.BoolVar(&complain, "complain", false, "Set complain flag on all profiles.")
flag.BoolVar(&enforce, "e", false, "Set enforce flag on all profiles.") flag.BoolVar(&enforce, "e", false, "Set enforce flag on all profiles.")
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.IntVar(&abi, "a", nilABI, "Target apparmor ABI.")
flag.UintVar(&abi, "abi", nilABI, "Target apparmor ABI.") flag.IntVar(&abi, "abi", nilABI, "Target apparmor ABI.")
flag.Float64Var(&version, "v", nilVer, "Target apparmor version.") flag.Float64Var(&version, "v", nilVer, "Target apparmor version.")
flag.Float64Var(&version, "version", nilVer, "Target apparmor version.") flag.Float64Var(&version, "version", nilVer, "Target apparmor version.")
flag.StringVar(&file, "F", "", "Only prebuild a given file.") flag.StringVar(&file, "F", "", "Only prebuild a given file.")

View file

@ -23,7 +23,7 @@ var (
regDirective = regexp.MustCompile(`(?m).*` + Keyword + `([a-z]*)( .*)?`) regDirective = regexp.MustCompile(`(?m).*` + Keyword + `([a-z]*)( .*)?`)
) )
// Main directive interface // Directive main interface
type Directive interface { type Directive interface {
prebuild.BaseInterface prebuild.BaseInterface
Apply(opt *Option, profile string) (string, error) Apply(opt *Option, profile string) (string, error)
@ -39,7 +39,7 @@ func Usage() string {
return res return res
} }
// Directive options // Option for the directive
type Option struct { type Option struct {
Name string Name string
ArgMap map[string]string ArgMap map[string]string
@ -83,7 +83,7 @@ func (o *Option) cleanKeyword(input string) string {
return reg.ReplaceAllString(input, "") return reg.ReplaceAllString(input, "")
} }
// Check if the directive is inline or if it is a paragraph // IsInline checks if either the directive is in one line or if it is a paragraph
func (o *Option) IsInline() bool { func (o *Option) IsInline() bool {
inline := true inline := true
tmp := strings.Split(o.Raw, Keyword) tmp := strings.Split(o.Raw, Keyword)
@ -106,7 +106,7 @@ func Run(file *paths.Path, profile string) (string, error) {
opt := NewOption(file, match) opt := NewOption(file, match)
drtv, ok := Directives[opt.Name] drtv, ok := Directives[opt.Name]
if !ok { if !ok {
return "", fmt.Errorf("Unknown directive '%s' in %s", opt.Name, opt.File) return "", fmt.Errorf("unknown directive '%s' in %s", opt.Name, opt.File)
} }
profile, err = drtv.Apply(opt, profile) profile, err = drtv.Apply(opt, profile)
if err != nil { if err != nil {

View file

@ -61,32 +61,32 @@ func (d Dbus) Apply(opt *Option, profile string) (string, error) {
generatedDbus := r.String() generatedDbus := r.String()
lenDbus := len(generatedDbus) lenDbus := len(generatedDbus)
generatedDbus = generatedDbus[:lenDbus-1] generatedDbus = generatedDbus[:lenDbus-1]
profile = strings.Replace(profile, opt.Raw, generatedDbus, -1) profile = strings.ReplaceAll(profile, opt.Raw, generatedDbus)
return profile, nil return profile, nil
} }
func (d Dbus) sanityCheck(opt *Option) (string, error) { func (d Dbus) sanityCheck(opt *Option) (string, error) {
if len(opt.ArgList) < 1 { if len(opt.ArgList) < 1 {
return "", fmt.Errorf("Unknown dbus action: %s in %s", opt.Name, opt.File) return "", fmt.Errorf("unknown dbus action: %s in %s", opt.Name, opt.File)
} }
action := opt.ArgList[0] action := opt.ArgList[0]
if action != "own" && action != "talk" && action != "common" { if action != "own" && action != "talk" && action != "common" {
return "", fmt.Errorf("Unknown dbus action: %s in %s", opt.Name, opt.File) return "", fmt.Errorf("unknown dbus action: %s in %s", opt.Name, opt.File)
} }
if _, present := opt.ArgMap["name"]; !present { if _, present := opt.ArgMap["name"]; !present {
return "", fmt.Errorf("Missing name for 'dbus: %s' in %s", action, opt.File) return "", fmt.Errorf("missing name for 'dbus: %s' in %s", action, opt.File)
} }
if _, present := opt.ArgMap["bus"]; !present { if _, present := opt.ArgMap["bus"]; !present {
return "", fmt.Errorf("Missing bus for '%s' in %s", opt.ArgMap["name"], opt.File) return "", fmt.Errorf("missing bus for '%s' in %s", opt.ArgMap["name"], opt.File)
} }
if _, present := opt.ArgMap["label"]; !present && action == "talk" { if _, present := opt.ArgMap["label"]; !present && action == "talk" {
return "", fmt.Errorf("Missing label for '%s' in %s", opt.ArgMap["name"], opt.File) return "", fmt.Errorf("missing label for '%s' in %s", opt.ArgMap["name"], opt.File)
} }
// Set default values // Set default values
if _, present := opt.ArgMap["path"]; !present { if _, present := opt.ArgMap["path"]; !present {
opt.ArgMap["path"] = "/" + strings.Replace(opt.ArgMap["name"], ".", "/", -1) + "{,/**}" opt.ArgMap["path"] = "/" + strings.ReplaceAll(opt.ArgMap["name"], ".", "/") + "{,/**}"
} }
opt.ArgMap["name"] += "{,.*}" opt.ArgMap["name"] += "{,.*}"
return action, nil return action, nil

View file

@ -31,7 +31,7 @@ func init() {
func (d Exec) Apply(opt *Option, profileRaw string) (string, error) { func (d Exec) Apply(opt *Option, profileRaw string) (string, error) {
if len(opt.ArgList) == 0 { if len(opt.ArgList) == 0 {
return "", fmt.Errorf("No profile to exec") return "", fmt.Errorf("no profile to exec")
} }
transition := "Px" transition := "Px"
transitions := []string{"P", "U", "p", "u", "PU", "pu"} transitions := []string{"P", "U", "p", "u", "PU", "pu"}
@ -70,5 +70,5 @@ func (d Exec) Apply(opt *Option, profileRaw string) (string, error) {
rules = rules.Sort() rules = rules.Sort()
new := rules.String() new := rules.String()
new = new[:len(new)-1] new = new[:len(new)-1]
return strings.Replace(profileRaw, opt.Raw, new, -1), nil return strings.ReplaceAll(profileRaw, opt.Raw, new), nil
} }

View file

@ -59,7 +59,7 @@ func filter(only bool, opt *Option, profile string) (string, error) {
} }
if opt.IsInline() { if opt.IsInline() {
profile = strings.Replace(profile, opt.Raw, "", -1) profile = strings.ReplaceAll(profile, opt.Raw, "")
} else { } else {
regRemoveParagraph := regexp.MustCompile(`(?s)` + opt.Raw + `\n.*?\n\n`) regRemoveParagraph := regexp.MustCompile(`(?s)` + opt.Raw + `\n.*?\n\n`)
profile = regRemoveParagraph.ReplaceAllString(profile, "") profile = regRemoveParagraph.ReplaceAllString(profile, "")

View file

@ -40,7 +40,7 @@ func init() {
func (s Stack) Apply(opt *Option, profile string) (string, error) { func (s Stack) Apply(opt *Option, profile string) (string, error) {
if len(opt.ArgList) == 0 { if len(opt.ArgList) == 0 {
return "", fmt.Errorf("No profile to stack") return "", fmt.Errorf("no profile to stack")
} }
t := opt.ArgList[0] t := opt.ArgList[0]
if t != "X" { if t != "X" {
@ -58,7 +58,7 @@ func (s Stack) Apply(opt *Option, profile string) (string, error) {
stackedProfile := prebuild.RootApparmord.Join(name).MustReadFileAsString() stackedProfile := prebuild.RootApparmord.Join(name).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)
} }
stackedRules := m[1] stackedRules := m[1]
stackedRules = regCleanStakedRules.Replace(stackedRules) stackedRules = regCleanStakedRules.Replace(stackedRules)
@ -68,9 +68,9 @@ func (s Stack) Apply(opt *Option, profile string) (string, error) {
// Insert the stacked profile at the end of the current profile, remove the stack directive // Insert the stacked profile at the end of the current profile, remove the stack directive
m := regEndOfRules.FindStringSubmatch(profile) m := regEndOfRules.FindStringSubmatch(profile)
if len(m) <= 1 { if len(m) <= 1 {
return "", fmt.Errorf("No end of rules found in %s", opt.File) return "", fmt.Errorf("no end of rules found in %s", opt.File)
} }
profile = strings.Replace(profile, m[0], res+m[0], -1) profile = strings.ReplaceAll(profile, m[0], res+m[0])
profile = strings.Replace(profile, opt.Raw, "", -1) profile = strings.ReplaceAll(profile, opt.Raw, "")
return profile, nil return profile, nil
} }

View file

@ -8,13 +8,13 @@ import "github.com/roddhjav/apparmor.d/pkg/paths"
var ( var (
// AppArmor ABI version // AppArmor ABI version
ABI uint = 0 ABI = 0
// AppArmor version // AppArmor version
Version float64 = 4.0 Version = 4.0
// Pkgname is the name of the package // Pkgname is the name of the package
Pkgname string = "apparmor.d" Pkgname = "apparmor.d"
// 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 = paths.New(".build")

View file

@ -10,7 +10,7 @@ import (
"github.com/roddhjav/apparmor.d/pkg/paths" "github.com/roddhjav/apparmor.d/pkg/paths"
) )
// Default content of debian/apparmor.d.hide. Whonix has special addition. // Hide is the default content of debian/apparmor.d.hide. Whonix has special addition.
var Hide = `# This file is generated by "make", all edit will be lost. var Hide = `# This file is generated by "make", all edit will be lost.
/etc/apparmor.d/usr.bin.firefox /etc/apparmor.d/usr.bin.firefox
@ -55,7 +55,7 @@ type DebianHider struct {
path *paths.Path path *paths.Path
} }
// Initialize the file with content from Hide // Init initializes the file with content from Hide
func (d DebianHider) Init() error { func (d DebianHider) Init() error {
return d.path.WriteFile([]byte(Hide)) return d.path.WriteFile([]byte(Hide))
} }

View file

@ -67,13 +67,13 @@ func getDistribution() string {
if id == "ubuntu" { if id == "ubuntu" {
return id return id
} }
id_like := Release["ID_LIKE"] idLike := Release["ID_LIKE"]
for main, based := range supportedDists { for main, based := range supportedDists {
if main == id || main == id_like { if main == id || main == idLike {
return main return main
} else if slices.Contains(based, id) { } else if slices.Contains(based, id) {
return main return main
} else if slices.Contains(based, id_like) { } else if slices.Contains(based, idLike) {
return main return main
} }
} }

View file

@ -18,7 +18,7 @@ var (
Tasks = map[string]Task{} Tasks = map[string]Task{}
) )
// Main directive interface // Task main directive interface
type Task interface { type Task interface {
prebuild.BaseInterface prebuild.BaseInterface
Apply() ([]string, error) Apply() ([]string, error)

View file

@ -39,8 +39,8 @@ func (p FullSystemPolicy) Apply() ([]string, error) {
if err != nil { if err != nil {
return res, err return res, err
} }
out = strings.Replace(out, "@{p_systemd}=unconfined", "@{p_systemd}=systemd", -1) out = strings.ReplaceAll(out, "@{p_systemd}=unconfined", "@{p_systemd}=systemd")
out = strings.Replace(out, "@{p_systemd_user}=unconfined", "@{p_systemd_user}=systemd-user", -1) out = strings.ReplaceAll(out, "@{p_systemd_user}=unconfined", "@{p_systemd_user}=systemd-user")
if err := path.WriteFile([]byte(out)); err != nil { if err := path.WriteFile([]byte(out)); err != nil {
return res, err return res, err
} }

View file

@ -17,14 +17,14 @@ import (
) )
type Tldr struct { type Tldr struct {
Url string // Tldr download url URL string // Tldr download url
Dir *paths.Path // Tldr cache directory Dir *paths.Path // Tldr cache directory
Ignore []string // List of ignored software Ignore []string // List of ignored software
} }
func NewTldr(dir *paths.Path) Tldr { func NewTldr(dir *paths.Path) Tldr {
return Tldr{ return Tldr{
Url: "https://github.com/tldr-pages/tldr/archive/refs/heads/main.tar.gz", URL: "https://github.com/tldr-pages/tldr/archive/refs/heads/main.tar.gz",
Dir: dir, Dir: dir,
} }
} }
@ -33,9 +33,9 @@ func NewTldr(dir *paths.Path) Tldr {
func (t Tldr) Download() error { func (t Tldr) Download() error {
gzPath := t.Dir.Parent().Join("tldr.tar.gz") gzPath := t.Dir.Parent().Join("tldr.tar.gz")
if !gzPath.Exist() { if !gzPath.Exist() {
resp, err := http.Get(t.Url) resp, err := http.Get(t.URL)
if err != nil { if err != nil {
return fmt.Errorf("downloading %s: %w", t.Url, err) return fmt.Errorf("downloading %s: %w", t.URL, err)
} }
defer resp.Body.Close() defer resp.Body.Close()