| 1 | package filter |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "regexp" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/ffuf/ffuf/v2/pkg/ffuf" |
| 10 | ) |
| 11 | |
| 12 | type RegexpFilter struct { |
| 13 | Value *regexp.Regexp |
| 14 | valueRaw string |
| 15 | } |
| 16 | |
| 17 | func NewRegexpFilter(value string) (ffuf.FilterProvider, error) { |
| 18 | re, err := regexp.Compile(value) |
| 19 | if err != nil { |
| 20 | return &RegexpFilter{}, fmt.Errorf("Regexp filter or matcher (-fr / -mr): invalid value: %s", value) |
| 21 | } |
| 22 | return &RegexpFilter{Value: re, valueRaw: value}, nil |
| 23 | } |
| 24 | |
| 25 | func (f *RegexpFilter) MarshalJSON() ([]byte, error) { |
| 26 | return json.Marshal(&struct { |
| 27 | Value string `json:"value"` |
| 28 | }{ |
| 29 | Value: f.valueRaw, |
| 30 | }) |
| 31 | } |
| 32 | |
| 33 | func (f *RegexpFilter) Filter(response *ffuf.Response) (bool, error) { |
| 34 | matchheaders := "" |
| 35 | for k, v := range response.Headers { |
| 36 | for _, iv := range v { |
| 37 | matchheaders += k + ": " + iv + "\r\n" |
| 38 | } |
| 39 | } |
| 40 | matchdata := []byte(matchheaders) |
| 41 | matchdata = append(matchdata, response.Data...) |
| 42 | pattern := f.valueRaw |
| 43 | for keyword, inputitem := range response.Request.Input { |
| 44 | pattern = strings.ReplaceAll(pattern, keyword, regexp.QuoteMeta(string(inputitem))) |
| 45 | } |
| 46 | matched, err := regexp.Match(pattern, matchdata) |
| 47 | if err != nil { |
| 48 | return false, nil |
| 49 | } |
| 50 | return matched, nil |
| 51 | } |
| 52 | |
| 53 | func (f *RegexpFilter) Repr() string { |
| 54 | return f.valueRaw |
| 55 | } |
| 56 | |
| 57 | func (f *RegexpFilter) ReprVerbose() string { |
| 58 | return fmt.Sprintf("Regexp: %s", f.valueRaw) |
| 59 | } |