Skip to content
File

Blob: waf/engine_test.go

go216 lines
1package waf
2 
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "io"
8 "mime/multipart"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "strings"
13 "testing"
14 
15 "go.miragespace.co/specter/spec/protocol"
16 
17 "github.com/go-chi/chi/v5/middleware"
18 "go.uber.org/zap"
19)
20 
21func testEngine(t testing.TB, limit int) *Engine {
22 t.Helper()
23 rules, err := bundledRules()
24 if err != nil {
25 t.Fatal(err)
26 }
27 engine, err := NewEngine(rules, bundledVersion, limit, zap.NewNop())
28 if err != nil {
29 t.Fatal(err)
30 }
31 t.Cleanup(func() { _ = engine.Close() })
32 return engine
33}
34 
35func multipartRequest(t testing.TB, size int) (string, []byte) {
36 t.Helper()
37 var body bytes.Buffer
38 writer := multipart.NewWriter(&body)
39 if err := writer.WriteField("description", "Holiday photograph"); err != nil {
40 t.Fatal(err)
41 }
42 file, err := writer.CreateFormFile("photo", "holiday.jpg")
43 if err != nil {
44 t.Fatal(err)
45 }
46 if _, err := io.CopyN(file, strings.NewReader(strings.Repeat("a", size)), int64(size)); err != nil {
47 t.Fatal(err)
48 }
49 if err := writer.Close(); err != nil {
50 t.Fatal(err)
51 }
52 return writer.FormDataContentType(), body.Bytes()
53}
54 
55func TestEngineBodies(t *testing.T) {
56 multipartType, multipartBody := multipartRequest(t, 256<<10)
57 largeJSON := []byte(`{"description":"` + strings.Repeat("a", 256<<10) + `"}`)
58 largeForm := []byte("description=" + strings.Repeat("%61", 100<<10))
59 deepJSON := []byte(strings.Repeat("[", 1025) + "0" + strings.Repeat("]", 1025) + strings.Repeat(" ", 256<<10))
60 partialAttack := []byte(`{"search":"1' OR 1=1--","padding":"` + strings.Repeat("a", 256<<10) + `"}`)
61 cases := []struct {
62 name string
63 contentType string
64 body []byte
65 status int
66 }{
67 {"form", "application/x-www-form-urlencoded", []byte("name=Rachel&message=Hello+world"), http.StatusNoContent},
68 {"json", "application/json", []byte(`{"name":"Rachel","message":"Hello world"}`), http.StatusNoContent},
69 {"large_form", "application/x-www-form-urlencoded", largeForm, http.StatusNoContent},
70 {"large_json", "application/json", largeJSON, http.StatusNoContent},
71 {"multipart", multipartType, multipartBody, http.StatusNoContent},
72 {"malformed_json", "application/json", []byte(`{"message":`), http.StatusBadRequest},
73 {"partial_json_depth_limit", "application/json", deepJSON, http.StatusBadRequest},
74 {"body_sqli", "application/x-www-form-urlencoded", []byte("search=" + url.QueryEscape("1' OR 1=1--")), http.StatusForbidden},
75 {"partial_json_sqli", "application/json", partialAttack, http.StatusForbidden},
76 }
77 engine := testEngine(t, DefaultBodyLimit)
78 for _, test := range cases {
79 t.Run(test.name, func(t *testing.T) {
80 request := httptest.NewRequest(http.MethodPost, "https://example.com/submit", bytes.NewReader(test.body))
81 request.Header.Set("Content-Type", test.contentType)
82 response := httptest.NewRecorder()
83 forwarded := false
84 engine.ServeHTTP(response, request, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
85 forwarded = true
86 body, err := io.ReadAll(r.Body)
87 if err != nil || !bytes.Equal(body, test.body) {
88 t.Fatalf("replayed body differs: bytes=%d err=%v", len(body), err)
89 }
90 w.WriteHeader(http.StatusNoContent)
91 }), "example.com", protocol.WAFPolicy_BLOCK, nil)
92 if response.Code != test.status {
93 t.Fatalf("status=%d want=%d body=%s", response.Code, test.status, response.Body.String())
94 }
95 if forwarded != (test.status == http.StatusNoContent) {
96 t.Fatalf("forwarded=%t", forwarded)
97 }
98 if len(engine.slots) != 0 {
99 t.Fatal("inspection admission was not released")
100 }
101 })
102 }
103}
104 
105func TestEngineRequests(t *testing.T) {
106 engine := testEngine(t, DefaultBodyLimit)
107 attack := url.QueryEscape("1' OR '1'='1' -- private-payload")
108 ctx := context.WithValue(t.Context(), middleware.RequestIDKey, "gateway/000001")
109 request := func(path string, mode protocol.WAFPolicy_Mode, ids []int) *httptest.ResponseRecorder {
110 r := httptest.NewRequestWithContext(ctx, http.MethodGet, "https://example.com"+path+"?search="+attack, nil)
111 r.Header.Set("X-Request-ID", "visitor-request-id")
112 w := httptest.NewRecorder()
113 engine.ServeHTTP(w, r, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
114 w.WriteHeader(http.StatusNoContent)
115 }), "test-tunnel", mode, ids)
116 return w
117 }
118 t.Run("exceptions and monitor", func(t *testing.T) {
119 blocked := request("/search", protocol.WAFPolicy_BLOCK, nil)
120 if blocked.Code != http.StatusForbidden {
121 t.Fatalf("SQLi status=%d body=%s", blocked.Code, blocked.Body.String())
122 }
123 var response denial
124 if err := json.Unmarshal(blocked.Body.Bytes(), &response); err != nil {
125 t.Fatal(err)
126 }
127 if response.RequestID != "gateway/000001" || response.Version != bundledVersion || len(response.Rules) == 0 {
128 t.Fatalf("missing safe denial information: %+v", response)
129 }
130 if strings.Contains(blocked.Body.String(), "private-payload") || strings.Contains(blocked.Body.String(), "/search") {
131 t.Fatal("denial leaked request data")
132 }
133 policy := &protocol.WAFPolicy{Mode: protocol.WAFPolicy_BLOCK}
134 for _, rule := range response.Rules {
135 if !rule.Excludable || rule.ID == 949110 {
136 t.Fatalf("non-detection rule in SQLi denial: %+v", rule)
137 }
138 policy.Exclusions = append(policy.Exclusions, &protocol.WAFExclusion{RuleId: uint32(rule.ID), Path: "/search"})
139 }
140 if w := request("/search", protocol.WAFPolicy_BLOCK, DisabledRules(policy, "/search")); w.Code != http.StatusNoContent {
141 t.Fatalf("exact-path exception failed: %d %s", w.Code, w.Body.String())
142 }
143 if w := request("/elsewhere", protocol.WAFPolicy_BLOCK, DisabledRules(policy, "/elsewhere")); w.Code != http.StatusForbidden {
144 t.Fatal("exception escaped its exact path")
145 }
146 if w := request("/search", protocol.WAFPolicy_BLOCK, []int{949110, 200002, 999999}); w.Code != http.StatusForbidden {
147 t.Fatal("protected or absent rule ID weakened enforcement")
148 }
149 if w := request("/search", protocol.WAFPolicy_MONITOR, nil); w.Code != http.StatusNoContent {
150 t.Fatal("monitor blocked the request")
151 }
152 })
153 t.Run("streaming body", func(t *testing.T) {
154 stream := &readProbe{Reader: strings.NewReader("stream content")}
155 r := httptest.NewRequest(http.MethodPost, "https://example.com/service", stream)
156 r.Header.Set("Content-Type", "application/grpc+proto")
157 w := httptest.NewRecorder()
158 engine.ServeHTTP(w, r, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
159 if stream.reads != 0 {
160 t.Fatal("gRPC stream was read before forwarding")
161 }
162 if _, err := io.Copy(io.Discard, r.Body); err != nil {
163 t.Fatal(err)
164 }
165 w.WriteHeader(http.StatusNoContent)
166 }), "example.com", protocol.WAFPolicy_BLOCK, nil)
167 if w.Code != http.StatusNoContent {
168 t.Fatalf("gRPC metadata-only request blocked: %d %s", w.Code, w.Body.String())
169 }
170 })
171 
172 t.Run("unread body holds admission", func(t *testing.T) {
173 // An upstream that does not consume its request body must keep the copied
174 // prefix charged to the admission limit, even though Coraza has closed.
175 slots := engine.slots
176 engine.slots = make(chan struct{}, 1)
177 defer func() { engine.slots = slots }()
178 func() {
179 entered, resume, finished := make(chan struct{}), make(chan struct{}), make(chan struct{})
180 go func() {
181 defer close(finished)
182 r := httptest.NewRequest(http.MethodPost, "https://example.com/submit", strings.NewReader(`{"message":"Hello"}`))
183 r.Header.Set("Content-Type", "application/json")
184 engine.ServeHTTP(httptest.NewRecorder(), r, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
185 close(entered)
186 <-resume
187 }), "example.com", protocol.WAFPolicy_BLOCK, nil)
188 }()
189 defer func() { close(resume); <-finished }()
190 <-entered
191 if w := request("/search", protocol.WAFPolicy_BLOCK, nil); w.Code != http.StatusServiceUnavailable {
192 t.Fatalf("retained prefix did not hold admission: %d", w.Code)
193 }
194 }()
195 if len(engine.slots) != 0 {
196 t.Fatal("closing an unread replay body did not release admission")
197 }
198 })
199 t.Run("retired generation", func(t *testing.T) {
200 _ = engine.Close()
201 if w := request("/search", protocol.WAFPolicy_BLOCK, nil); w.Code != http.StatusForbidden {
202 t.Fatal("retirement interrupted an already-selected generation")
203 }
204 })
205}
206 
207type readProbe struct {
208 io.Reader
209 reads int
210}
211 
212func (r *readProbe) Read(p []byte) (int, error) {
213 r.reads++
214 return r.Reader.Read(p)
215}