2023-04-17 00:26:46 +02:00
|
|
|
// apparmor.d - Full set of apparmor profiles
|
2024-02-07 00:16:21 +01:00
|
|
|
// Copyright (C) 2023-2024 Alexandre Pujol <alexandre@pujol.io>
|
2023-04-17 00:26:46 +02:00
|
|
|
// SPDX-License-Identifier: GPL-2.0-only
|
|
|
|
|
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/hex"
|
|
|
|
"regexp"
|
|
|
|
)
|
|
|
|
|
2024-04-02 18:48:03 +02:00
|
|
|
var (
|
|
|
|
Comment = `#`
|
|
|
|
regFilter = ToRegexRepl([]string{
|
|
|
|
`\s*` + Comment + `.*`, ``,
|
|
|
|
`(?m)^(?:[\t\s]*(?:\r?\n|\r))+`, ``,
|
|
|
|
})
|
2024-04-28 13:06:40 +02:00
|
|
|
regHex = map[string]*regexp.Regexp{
|
|
|
|
"name": regexp.MustCompile(`name=[0-9A-F]+`),
|
|
|
|
"comm": regexp.MustCompile(`comm=[0-9A-F]+`),
|
|
|
|
"profile": regexp.MustCompile(`profile=[0-9A-F]+`),
|
|
|
|
}
|
2024-04-02 18:48:03 +02:00
|
|
|
)
|
|
|
|
|
2024-03-10 16:53:25 +01:00
|
|
|
type RegexReplList []RegexRepl
|
|
|
|
|
2023-07-23 18:00:52 +02:00
|
|
|
type RegexRepl struct {
|
|
|
|
Regex *regexp.Regexp
|
|
|
|
Repl string
|
|
|
|
}
|
|
|
|
|
2024-03-21 19:54:52 +01:00
|
|
|
// ToRegexRepl convert slice of regex into a slice of RegexRepl
|
|
|
|
func ToRegexRepl(in []string) RegexReplList {
|
2024-04-28 13:06:40 +02:00
|
|
|
out := make([]RegexRepl, 0, len(in)/2)
|
2024-03-21 19:54:52 +01:00
|
|
|
idx := 0
|
|
|
|
for idx < len(in)-1 {
|
|
|
|
regex, repl := in[idx], in[idx+1]
|
|
|
|
out = append(out, RegexRepl{
|
|
|
|
Regex: regexp.MustCompile(regex),
|
|
|
|
Repl: repl,
|
|
|
|
})
|
|
|
|
idx = idx + 2
|
|
|
|
}
|
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rr RegexReplList) Replace(str string) string {
|
|
|
|
for _, aa := range rr {
|
|
|
|
str = aa.Regex.ReplaceAllLiteralString(str, aa.Repl)
|
|
|
|
}
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
|
2024-04-02 18:48:03 +02:00
|
|
|
// DecodeHexInString decode and replace all hex value in a given string of "key=value" format.
|
2023-10-11 00:47:31 +02:00
|
|
|
func DecodeHexInString(str string) string {
|
2024-04-28 13:06:40 +02:00
|
|
|
for name, re := range regHex {
|
2023-10-11 00:47:31 +02:00
|
|
|
str = re.ReplaceAllStringFunc(str, func(s string) string {
|
|
|
|
hexa := s[len(name)+1:]
|
|
|
|
bs, _ := hex.DecodeString(hexa)
|
|
|
|
return name + "=\"" + string(bs) + "\""
|
|
|
|
})
|
2023-04-17 00:26:46 +02:00
|
|
|
}
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
|
2024-04-02 18:48:03 +02:00
|
|
|
// Filter out comments and empty line from a string
|
|
|
|
func Filter(src string) string {
|
|
|
|
return regFilter.Replace(src)
|
|
|
|
}
|