forked from corazawaf/coraza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restpath.go
59 lines (48 loc) · 1.57 KB
/
restpath.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
56
57
58
59
// Copyright 2022 Juan Pablo Tosso and the OWASP Coraza contributors
// SPDX-License-Identifier: Apache-2.0
//go:build !coraza.disabled_operators.restpath
package operators
import (
"fmt"
"regexp"
"strings"
"github.com/crowdsecurity/coraza/v3/experimental/plugins/plugintypes"
"github.com/crowdsecurity/coraza/v3/internal/memoize"
)
var rePathTokenRe = regexp.MustCompile(`\{([^\}]+)\}`)
// @restpath takes as argument a path expression in the format
// /path/to/resource/{id}/{name}/{age}
// It will later transform the path to a regex and assign the variables to
// ARGS_PATH
type restpath struct {
re *regexp.Regexp
}
var _ plugintypes.Operator = (*restpath)(nil)
func newRESTPath(options plugintypes.OperatorOptions) (plugintypes.Operator, error) {
data := strings.ReplaceAll(options.Arguments, "/", "\\/")
for _, token := range rePathTokenRe.FindAllStringSubmatch(data, -1) {
data = strings.Replace(data, token[0], fmt.Sprintf("(?P<%s>.*)", token[1]), 1)
}
re, err := memoize.Do(data, func() (interface{}, error) { return regexp.Compile(data) })
if err != nil {
return nil, err
}
return &restpath{re: re.(*regexp.Regexp)}, nil
}
func (o *restpath) Evaluate(tx plugintypes.TransactionState, value string) bool {
// we use the re regex to match the path and match named captured groups
// to the ARGS_PATH
match := o.re.FindStringSubmatch(value)
if len(match) == 0 {
return false
}
for i, m := range o.re.SubexpNames() {
if i != 0 && m != "" {
tx.Variables().ArgsPath().SetIndex(m, 0, match[i])
}
}
return true
}
func init() {
Register("restpath", newRESTPath)
}