Skip to content
File

Blob: waf/engine.go

go444 lines
1package waf
2 
3import (
4 "bytes"
5 "crypto/rand"
6 _ "embed"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "html/template"
11 "io"
12 "io/fs"
13 "mime"
14 "net"
15 "net/http"
16 "slices"
17 "strconv"
18 "strings"
19 "sync"
20 "time"
21 
22 "go.miragespace.co/specter/spec/protocol"
23 
24 corazaconf "github.com/corazawaf/coraza-coreruleset/coraza/v3"
25 "github.com/corazawaf/coraza/v3"
26 "github.com/corazawaf/coraza/v3/experimental"
27 "github.com/corazawaf/coraza/v3/types"
28 "github.com/go-chi/chi/v5/middleware"
29 "go.uber.org/zap"
30)
31 
32const (
33 EngineVersion = "3.8.1"
34 // DefaultBodyLimit bounds inspection, not the size of a forwarded upload.
35 DefaultBodyLimit = 16 << 10
36 maxVariants = 32
37 maxInspections = 32
38 bodyReadTimeout = 15 * time.Second
39)
40 
41type RuleInfo struct {
42 ID int `json:"id"`
43 Category string `json:"category"`
44 Excludable bool `json:"excludable"`
45}
46 
47type engineVariant struct {
48 waf coraza.WAF
49 used uint64
50}
51 
52// Engine owns one immutable rules release and a bounded set of compiled policy
53// variants. The cache is shared by requests with identical effective exceptions.
54type Engine struct {
55 rules fs.FS
56 version string
57 bodyLimit int
58 config string
59 logger *zap.Logger
60 catalog map[int]RuleInfo
61 slots chan struct{}
62 
63 mu sync.Mutex
64 variants map[string]engineVariant
65 clock uint64
66 closed bool
67}
68 
69// NewEngine expects the official CRS archive layout: crs-setup.conf.example and
70// rules/*.conf, including the data files referenced by those rules.
71func NewEngine(rules fs.FS, version string, bodyLimit int, logger *zap.Logger) (*Engine, error) {
72 if bodyLimit <= 0 || bodyLimit > 1<<20 {
73 return nil, errors.New("WAF inspection limit must be between 1 byte and 1 MiB")
74 }
75 if logger == nil {
76 logger = zap.NewNop()
77 }
78 config, err := fs.ReadFile(corazaconf.FS, "@coraza.conf-recommended")
79 if err != nil {
80 return nil, fmt.Errorf("load Coraza configuration: %w", err)
81 }
82 e := &Engine{
83 rules: rules, version: version, bodyLimit: bodyLimit,
84 config: string(config), logger: logger,
85 catalog: make(map[int]RuleInfo), slots: make(chan struct{}, maxInspections),
86 variants: make(map[string]engineVariant),
87 }
88 for _, mode := range []protocol.WAFPolicy_Mode{protocol.WAFPolicy_BLOCK, protocol.WAFPolicy_MONITOR} {
89 waf, err := e.compile(mode, nil, mode == protocol.WAFPolicy_BLOCK)
90 if err != nil {
91 e.Close()
92 return nil, err
93 }
94 e.variants[mode.String()] = engineVariant{waf: waf}
95 }
96 if len(e.catalog) == 0 {
97 e.Close()
98 return nil, errors.New("CRS did not load any request detection rules")
99 }
100 return e, nil
101}
102 
103func (e *Engine) compile(mode protocol.WAFPolicy_Mode, disabled []int, catalog bool) (coraza.WAF, error) {
104 engineMode := "On"
105 if mode == protocol.WAFPolicy_MONITOR {
106 engineMode = "DetectionOnly"
107 }
108 cfg := coraza.NewWAFConfig().WithRootFS(e.rules).
109 WithDirectives(e.config).
110 WithDirectives(engineProfile).
111 WithDirectivesFromFile("crs-setup.conf.example").
112 WithDirectivesFromFile("rules/*.conf").
113 WithDirectives(tunnelProfile).
114 WithDirectives("SecRuleEngine " + engineMode).
115 WithRequestBodyLimit(e.bodyLimit).
116 WithRequestBodyInMemoryLimit(e.bodyLimit)
117 for _, id := range disabled {
118 cfg = cfg.WithDirectives("SecRuleRemoveById " + strconv.Itoa(id))
119 }
120 if catalog {
121 cfg = experimental.WAFConfigWithRuleObserver(cfg, func(rule types.RuleMetadata) {
122 if eligibleRule(rule) {
123 e.catalog[rule.ID()] = RuleInfo{ID: rule.ID(), Category: ruleCategory(rule.Tags()), Excludable: true}
124 }
125 })
126 }
127 waf, err := coraza.NewWAF(cfg)
128 if err != nil {
129 return nil, fmt.Errorf("compile CRS %s: %w", e.version, err)
130 }
131 return waf, nil
132}
133 
134func eligibleRule(rule types.RuleMetadata) bool {
135 id := rule.ID()
136 if id < 911000 || id >= 949000 || id == 911100 || id == 920420 || rule.SecMark() != "" {
137 return false
138 }
139 if rule.Phase() != types.PhaseRequestHeaders && rule.Phase() != types.PhaseRequestBody {
140 return false
141 }
142 tags := rule.Tags()
143 return slices.Contains(tags, "OWASP_CRS") && slices.ContainsFunc(tags, func(tag string) bool {
144 return strings.HasPrefix(tag, "attack-")
145 })
146}
147 
148func (e *Engine) variant(mode protocol.WAFPolicy_Mode, disabled []int) (coraza.WAF, error) {
149 ids := make([]int, 0, len(disabled))
150 for _, id := range disabled {
151 if _, ok := e.catalog[id]; ok {
152 ids = append(ids, id)
153 }
154 }
155 slices.Sort(ids)
156 ids = slices.Compact(ids)
157 var key strings.Builder
158 key.WriteString(mode.String())
159 for _, id := range ids {
160 key.WriteByte(':')
161 key.WriteString(strconv.Itoa(id))
162 }
163 k := key.String()
164 e.mu.Lock()
165 defer e.mu.Unlock()
166 e.clock++
167 if cached, ok := e.variants[k]; ok {
168 cached.used = e.clock
169 e.variants[k] = cached
170 return cached.waf, nil
171 }
172 waf, err := e.compile(mode, ids, false)
173 if err != nil {
174 return nil, err
175 }
176 if e.closed {
177 // A manager may retire this generation after a request loaded its pointer.
178 // Closing only releases memoized ownership; this WAF remains usable.
179 closeWAF(waf)
180 return waf, nil
181 }
182 if len(e.variants) >= maxVariants {
183 var oldestKey string
184 oldest := ^uint64(0)
185 for key, entry := range e.variants {
186 if key != protocol.WAFPolicy_BLOCK.String() && key != protocol.WAFPolicy_MONITOR.String() && entry.used < oldest {
187 oldestKey, oldest = key, entry.used
188 }
189 }
190 closeWAF(e.variants[oldestKey].waf)
191 delete(e.variants, oldestKey)
192 }
193 e.variants[k] = engineVariant{waf: waf, used: e.clock}
194 return waf, nil
195}
196 
197func closeWAF(waf coraza.WAF) {
198 if closer, ok := waf.(experimental.WAFCloser); ok {
199 _ = closer.Close()
200 }
201}
202 
203// Close retires the cache without interrupting requests holding this generation.
204func (e *Engine) Close() error {
205 e.mu.Lock()
206 defer e.mu.Unlock()
207 if !e.closed {
208 e.closed = true
209 for _, entry := range e.variants {
210 closeWAF(entry.waf)
211 }
212 }
213 return nil
214}
215 
216func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.Handler, hostname string, mode protocol.WAFPolicy_Mode, disabledIDs []int) {
217 if mode == protocol.WAFPolicy_OFF {
218 next.ServeHTTP(w, r)
219 return
220 }
221 if mode != protocol.WAFPolicy_BLOCK && mode != protocol.WAFPolicy_MONITOR {
222 http.Error(w, "Web protection configuration is unavailable", http.StatusServiceUnavailable)
223 return
224 }
225 select {
226 case e.slots <- struct{}{}:
227 default:
228 http.Error(w, "Web protection is busy; please retry", http.StatusServiceUnavailable)
229 return
230 }
231 release := sync.OnceFunc(func() { <-e.slots })
232 defer release()
233 requestID := middleware.GetReqID(r.Context())
234 prefix, interrupted, matched, err := e.inspect(w, r, mode, disabledIDs, requestID)
235 if err != nil {
236 e.logger.Warn("WAF inspection failed",
237 zap.String("hostname", hostname), zap.String("request_id", requestID),
238 zap.String("rules_version", e.version), zap.String("mode", mode.String()))
239 http.Error(w, "Unable to inspect request", http.StatusBadRequest)
240 return
241 }
242 if len(matched) > 0 {
243 ids := make([]int, 0, len(matched))
244 for _, rule := range matched {
245 ids = append(ids, rule.ID)
246 }
247 e.logger.Info("WAF rule matches",
248 zap.String("hostname", hostname), zap.String("request_id", requestID),
249 zap.String("rules_version", e.version), zap.String("mode", mode.String()),
250 zap.Ints("rule_ids", ids), zap.Bool("blocked", interrupted != nil))
251 }
252 if interrupted != nil {
253 status := interrupted.Status
254 if status < 400 || status > 599 {
255 status = http.StatusForbidden
256 }
257 writeDenial(w, r, status, denial{Error: "request_blocked", RequestID: requestID, Version: e.version, Rules: matched})
258 return
259 }
260 if len(prefix) > 0 {
261 body := &replayBody{prefix: bytes.NewReader(prefix), source: r.Body, release: release}
262 r.Body = body
263 defer body.Close()
264 } else {
265 release()
266 }
267 next.ServeHTTP(w, r)
268}
269 
270func (e *Engine) inspect(w http.ResponseWriter, r *http.Request, mode protocol.WAFPolicy_Mode, disabled []int, requestID string) ([]byte, *types.Interruption, []RuleInfo, error) {
271 waf, err := e.variant(mode, disabled)
272 if err != nil {
273 return nil, nil, nil, err
274 }
275 tx := waf.NewTransactionWithID(requestID)
276 defer func() {
277 tx.ProcessLogging()
278 _ = tx.Close()
279 }()
280 client, clientPort := splitAddress(r.RemoteAddr)
281 server, serverPort := "", 0
282 if addr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
283 server, serverPort = splitAddress(addr.String())
284 }
285 tx.ProcessConnection(client, clientPort, server, serverPort)
286 tx.ProcessURI(r.URL.RequestURI(), r.Method, r.Proto)
287 tx.SetServerName(r.Host)
288 tx.AddRequestHeader("Host", r.Host)
289 for key, values := range r.Header {
290 if strings.EqualFold(key, "Host") {
291 continue
292 }
293 for _, value := range values {
294 tx.AddRequestHeader(key, value)
295 }
296 }
297 if r.ContentLength > 0 && r.Header.Get("Content-Length") == "" {
298 tx.AddRequestHeader("Content-Length", strconv.FormatInt(r.ContentLength, 10))
299 }
300 for _, encoding := range r.TransferEncoding {
301 tx.AddRequestHeader("Transfer-Encoding", encoding)
302 }
303 if interruption := tx.ProcessRequestHeaders(); interruption != nil {
304 return nil, interruption, e.matches(tx), nil
305 }
306 var prefix []byte
307 if r.Body != nil && r.Body != http.NoBody && inspectBody(r.Header.Get("Content-Type")) {
308 controller := http.NewResponseController(w)
309 if err := controller.SetReadDeadline(time.Now().Add(bodyReadTimeout)); err == nil {
310 defer controller.SetReadDeadline(time.Time{})
311 }
312 interruption, _, err := tx.ReadRequestBodyFrom(r.Body)
313 if err != nil || interruption != nil {
314 return nil, interruption, e.matches(tx), err
315 }
316 reader, err := tx.RequestBodyReader()
317 if err != nil {
318 return nil, nil, nil, err
319 }
320 prefix, err = io.ReadAll(reader)
321 if err != nil {
322 return nil, nil, nil, err
323 }
324 }
325 interruption, err := tx.ProcessRequestBody()
326 return prefix, interruption, e.matches(tx), err
327}
328 
329func splitAddress(address string) (string, int) {
330 host, port, err := net.SplitHostPort(address)
331 if err != nil {
332 return address, 0
333 }
334 n, _ := strconv.Atoi(port)
335 return host, n
336}
337 
338func inspectBody(contentType string) bool {
339 mediaType, _, err := mime.ParseMediaType(contentType)
340 if err != nil {
341 return false
342 }
343 if strings.HasPrefix(mediaType, "application/grpc") || strings.HasPrefix(mediaType, "application/connect+") || mediaType == "application/stream+json" {
344 return false
345 }
346 return mediaType == "application/x-www-form-urlencoded" || mediaType == "multipart/form-data" ||
347 mediaType == "application/json" || mediaType == "application/xml" || mediaType == "application/soap+xml" ||
348 mediaType == "text/xml" || (strings.HasPrefix(mediaType, "application/") && strings.HasSuffix(mediaType, "+json"))
349}
350 
351func (e *Engine) matches(tx types.Transaction) []RuleInfo {
352 var matches []RuleInfo
353 for _, match := range tx.MatchedRules() {
354 if rule, ok := e.catalog[match.Rule().ID()]; ok {
355 matches = append(matches, rule)
356 }
357 }
358 slices.SortFunc(matches, func(a, b RuleInfo) int { return a.ID - b.ID })
359 matches = slices.CompactFunc(matches, func(a, b RuleInfo) bool { return a.ID == b.ID })
360 if len(matches) == 0 && tx.Interruption() != nil {
361 matches = append(matches, RuleInfo{ID: tx.Interruption().RuleID, Category: "Request format"})
362 }
363 return matches
364}
365 
366// replayBody owns only the copied prefix and the original request body. Coraza's
367// transaction is already closed. Admission stays charged until that prefix is
368// consumed or the body closes, including when the upstream never reads it.
369type replayBody struct {
370 mu sync.Mutex
371 prefix *bytes.Reader
372 source io.ReadCloser
373 release func()
374 closed bool
375 close sync.Once
376 err error
377}
378 
379func (b *replayBody) Read(p []byte) (int, error) {
380 b.mu.Lock()
381 if b.closed {
382 b.mu.Unlock()
383 return 0, io.ErrClosedPipe
384 }
385 if b.prefix != nil {
386 n, _ := b.prefix.Read(p)
387 if b.prefix.Len() == 0 {
388 b.prefix = nil
389 b.release()
390 }
391 b.mu.Unlock()
392 if n > 0 {
393 return n, nil
394 }
395 } else {
396 b.mu.Unlock()
397 }
398 return b.source.Read(p)
399}
400 
401func (b *replayBody) Close() error {
402 b.close.Do(func() {
403 b.mu.Lock()
404 b.closed = true
405 b.prefix = nil
406 b.release()
407 b.mu.Unlock()
408 b.err = b.source.Close()
409 })
410 return b.err
411}
412 
413type denial struct {
414 Error string `json:"error"`
415 RequestID string `json:"request_id"`
416 Version string `json:"rules_version"`
417 Rules []RuleInfo `json:"rules"`
418 CanExclude bool `json:"-"`
419 Nonce string `json:"-"`
420}
421 
422//go:embed blocked.html
423var denialHTML string
424 
425var denialPage = template.Must(template.New("waf-denial").Parse(denialHTML))
426 
427func writeDenial(w http.ResponseWriter, r *http.Request, status int, response denial) {
428 response.CanExclude = slices.ContainsFunc(response.Rules, func(rule RuleInfo) bool { return rule.Excludable })
429 w.Header().Set("Cache-Control", "no-store")
430 w.Header().Set("X-Content-Type-Options", "nosniff")
431 w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
432 if strings.Contains(r.Header.Get("Accept"), "text/html") {
433 response.Nonce = rand.Text()
434 w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'nonce-"+response.Nonce+"'; frame-ancestors 'none'; base-uri 'none'")
435 w.Header().Set("Content-Type", "text/html; charset=utf-8")
436 w.WriteHeader(status)
437 _ = denialPage.Execute(w, response)
438 return
439 }
440 w.Header().Set("Content-Type", "application/json; charset=utf-8")
441 w.WriteHeader(status)
442 _ = json.NewEncoder(w).Encode(response)
443}