| 1 | package filter |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/ffuf/ffuf/v2/pkg/ffuf" |
| 10 | ) |
| 11 | |
| 12 | const AllStatuses = 0 |
| 13 | |
| 14 | type StatusFilter struct { |
| 15 | Value []ffuf.ValueRange |
| 16 | } |
| 17 | |
| 18 | func NewStatusFilter(value string) (ffuf.FilterProvider, error) { |
| 19 | var intranges []ffuf.ValueRange |
| 20 | for _, sv := range strings.Split(value, ",") { |
| 21 | if sv == "all" { |
| 22 | intranges = append(intranges, ffuf.ValueRange{Min: AllStatuses, Max: AllStatuses}) |
| 23 | } else { |
| 24 | vr, err := ffuf.ValueRangeFromString(sv) |
| 25 | if err != nil { |
| 26 | return &StatusFilter{}, fmt.Errorf("Status filter or matcher (-fc / -mc): invalid value %s", sv) |
| 27 | } |
| 28 | intranges = append(intranges, vr) |
| 29 | } |
| 30 | } |
| 31 | return &StatusFilter{Value: intranges}, nil |
| 32 | } |
| 33 | |
| 34 | func (f *StatusFilter) MarshalJSON() ([]byte, error) { |
| 35 | value := make([]string, 0) |
| 36 | for _, v := range f.Value { |
| 37 | if v.Min == 0 && v.Max == 0 { |
| 38 | value = append(value, "all") |
| 39 | } else { |
| 40 | if v.Min == v.Max { |
| 41 | value = append(value, strconv.FormatInt(v.Min, 10)) |
| 42 | } else { |
| 43 | value = append(value, fmt.Sprintf("%d-%d", v.Min, v.Max)) |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | return json.Marshal(&struct { |
| 48 | Value string `json:"value"` |
| 49 | }{ |
| 50 | Value: strings.Join(value, ","), |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | func (f *StatusFilter) Filter(response *ffuf.Response) (bool, error) { |
| 55 | for _, iv := range f.Value { |
| 56 | if iv.Min == AllStatuses && iv.Max == AllStatuses { |
| 57 | // Handle the "all" case |
| 58 | return true, nil |
| 59 | } |
| 60 | if iv.Min <= response.StatusCode && response.StatusCode <= iv.Max { |
| 61 | return true, nil |
| 62 | } |
| 63 | } |
| 64 | return false, nil |
| 65 | } |
| 66 | |
| 67 | func (f *StatusFilter) Repr() string { |
| 68 | var strval []string |
| 69 | for _, iv := range f.Value { |
| 70 | if iv.Min == AllStatuses && iv.Max == AllStatuses { |
| 71 | strval = append(strval, "all") |
| 72 | } else if iv.Min == iv.Max { |
| 73 | strval = append(strval, strconv.Itoa(int(iv.Min))) |
| 74 | } else { |
| 75 | strval = append(strval, strconv.Itoa(int(iv.Min))+"-"+strconv.Itoa(int(iv.Max))) |
| 76 | } |
| 77 | } |
| 78 | return strings.Join(strval, ",") |
| 79 | } |
| 80 | |
| 81 | func (f *StatusFilter) ReprVerbose() string { |
| 82 | return fmt.Sprintf("Response status: %s", f.Repr()) |
| 83 | } |