forked from corazawaf/coraza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pm_from_file.go
55 lines (43 loc) · 1.3 KB
/
pm_from_file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright 2022 Juan Pablo Tosso and the OWASP Coraza contributors
// SPDX-License-Identifier: Apache-2.0
//go:build !coraza.disabled_operators.pmFromFile
package operators
import (
"bufio"
"bytes"
"strings"
ahocorasick "github.com/petar-dambovaliev/aho-corasick"
"github.com/crowdsecurity/coraza/v3/experimental/plugins/plugintypes"
"github.com/crowdsecurity/coraza/v3/internal/memoize"
)
func newPMFromFile(options plugintypes.OperatorOptions) (plugintypes.Operator, error) {
filepath := options.Arguments
data, err := loadFromFile(filepath, options.Path, options.Root)
if err != nil {
return nil, err
}
var lines []string
sc := bufio.NewScanner(bytes.NewReader(data))
for sc.Scan() {
l := sc.Text()
l = strings.TrimSpace(l)
if len(l) == 0 {
continue
}
if l[0] == '#' {
continue
}
lines = append(lines, strings.ToLower(l))
}
builder := ahocorasick.NewAhoCorasickBuilder(ahocorasick.Opts{
AsciiCaseInsensitive: true,
MatchOnlyWholeWords: false,
MatchKind: ahocorasick.LeftMostLongestMatch,
DFA: false,
})
m, _ := memoize.Do(strings.Join(options.Path, ",")+filepath, func() (interface{}, error) { return builder.Build(lines), nil })
return &pm{matcher: m.(ahocorasick.AhoCorasick)}, nil
}
func init() {
Register("pmFromFile", newPMFromFile)
}