-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathcoraza.go
More file actions
308 lines (269 loc) · 8.21 KB
/
Copy pathcoraza.go
File metadata and controls
308 lines (269 loc) · 8.21 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Copyright 2025 The OWASP Coraza contributors
// SPDX-License-Identifier: Apache-2.0
package coraza
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"path/filepath"
"sort"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
coreruleset "github.com/corazawaf/coraza-coreruleset/v4"
"github.com/corazawaf/coraza/v3"
"github.com/corazawaf/coraza/v3/types"
"github.com/jcchavezs/mergefs"
mergefsio "github.com/jcchavezs/mergefs/io"
"go.uber.org/zap"
)
// wafPool is a process-global pool that allows WAF instances to be shared
// across Caddy config reloads. When two consecutive configs use the same
// WAF configuration, the pool returns the existing WAF instead of building
// a new one, saving both memory and CPU.
var wafPool = caddy.NewUsagePool()
func init() {
caddy.RegisterModule(corazaModule{})
httpcaddyfile.RegisterHandlerDirective("coraza_waf", parseCaddyfile)
}
// pooledWAF wraps a coraza.WAF so it can be stored in a caddy.UsagePool.
// It implements caddy.Destructor so the pool can clean it up when all
// references are released.
type pooledWAF struct {
waf coraza.WAF
}
func (p *pooledWAF) Destruct() error {
var err error
if c, ok := p.waf.(io.Closer); ok {
if cerr := c.Close(); cerr != nil {
err = fmt.Errorf("closing WAF: %w", cerr)
}
}
p.waf = nil
return err
}
// corazaModule is a Web Application Firewall implementation for Caddy.
type corazaModule struct {
// deprecated
Include []string `json:"include"`
Directives string `json:"directives"`
LoadOWASPCRS bool `json:"load_owasp_crs"`
logger *zap.Logger
waf coraza.WAF
poolKey string
}
// CaddyModule returns the Caddy module information.
func (corazaModule) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.waf",
New: func() caddy.Module { return new(corazaModule) },
}
}
// Provision implements caddy.Provisioner.
func (m *corazaModule) Provision(ctx caddy.Context) error {
m.logger = ctx.Logger(m)
m.poolKey = m.computePoolKey()
val, loaded, err := wafPool.LoadOrNew(m.poolKey, func() (caddy.Destructor, error) {
waf, err := m.buildWAF()
if err != nil {
return nil, err
}
return &pooledWAF{waf: waf}, nil
})
if err != nil {
return err
}
m.waf = val.(*pooledWAF).waf
if loaded {
m.logger.Info("reusing existing WAF instance from pool")
}
return nil
}
// buildWAF creates a new coraza.WAF from the module's configuration.
func (m *corazaModule) buildWAF() (coraza.WAF, error) {
config := coraza.NewWAFConfig().
WithErrorCallback(newErrorCb(m.logger)).
WithDebugLogger(newLogger(m.logger))
if m.LoadOWASPCRS {
config = config.WithRootFS(mergefs.Merge(coreruleset.FS, mergefsio.OSFS))
}
if m.Directives != "" {
config = config.WithDirectives(m.Directives)
}
if len(m.Include) > 0 {
m.logger.Warn("'include' field is deprecated, please use the Include directive inside 'directives' field instead")
for _, file := range m.Include {
if strings.Contains(file, "*") {
m.logger.Debug("Preparing to expand glob", zap.String("pattern", file))
// we get files as expandables globs (with wildcard patterns)
fs, err := filepath.Glob(file)
if err != nil {
return nil, err
}
m.logger.Debug("Glob expanded", zap.String("pattern", file), zap.Strings("files", fs))
for _, f := range fs {
config = config.WithDirectivesFromFile(f)
}
} else {
m.logger.Debug("File was not a pattern, compiling it", zap.String("file", file))
config = config.WithDirectivesFromFile(file)
}
}
}
return coraza.NewWAF(config)
}
// computePoolKey returns a deterministic key derived from the configuration
// fields that affect WAF construction. Two modules with identical configs
// will produce the same key, enabling WAF reuse across reloads.
func (m *corazaModule) computePoolKey() string {
h := sha256.New()
h.Write([]byte(m.Directives))
h.Write([]byte{0}) // separator
sorted := make([]string, len(m.Include))
copy(sorted, m.Include)
sort.Strings(sorted)
for _, inc := range sorted {
h.Write([]byte(inc))
h.Write([]byte{0})
}
if m.LoadOWASPCRS {
h.Write([]byte("crs"))
}
return fmt.Sprintf("coraza-waf-%x", h.Sum(nil))
}
// Validate implements caddy.Validator.
func (m *corazaModule) Validate() error {
return nil
}
// Cleanup implements caddy.CleanerUpper.
func (m *corazaModule) Cleanup() error {
_, err := wafPool.Delete(m.poolKey)
return err
}
var errInterruptionTriggered = errors.New("interruption triggered")
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (m corazaModule) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
id := randomString(16)
tx := m.waf.NewTransactionWithID(id)
defer func() {
tx.ProcessLogging()
if err := tx.Close(); err != nil {
m.logger.Warn("Failed to close the transaction", zap.String("tx_id", tx.ID()), zap.Error(err))
}
}()
// Early return, Coraza is not going to process any rule
if tx.IsRuleEngineOff() {
// response writer is not going to be wrapped, but used as-is
// to generate the response
return next.ServeHTTP(w, r)
}
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
repl.Set("http.transaction_id", id)
server := r.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server)
caddyhttp.PrepareRequest(r, repl, w, server)
// ProcessRequest is just a wrapper around ProcessConnection, ProcessURI,
// ProcessRequestHeaders and ProcessRequestBody.
// It fails if any of these functions returns an error and it stops on interruption.
if it, err := processRequest(tx, r); err != nil {
return caddyhttp.HandlerError{
StatusCode: http.StatusInternalServerError,
ID: tx.ID(),
Err: err,
}
} else if it != nil {
client, _ := getClientAddress(r)
m.logger.Error("WAF rule violation detected",
zap.String("hostname", r.Host),
zap.String("uri", r.RequestURI),
zap.String("client_ip", client),
zap.String("unique_id", tx.ID()),
)
return caddyhttp.HandlerError{
StatusCode: obtainStatusCodeFromInterruptionOrDefault(it, http.StatusOK),
ID: tx.ID(),
Err: errInterruptionTriggered,
}
}
ww, processResponse := wrap(w, r, tx)
// We continue with the other middlewares by catching the response
if err := next.ServeHTTP(ww, r); err != nil {
return err
}
return processResponse(tx, r)
}
// Unmarshal Caddyfile implements caddyfile.Unmarshaler.
func (m *corazaModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if !d.Next() {
return d.Err("expected token following filter")
}
m.Include = []string{}
for d.NextBlock(0) {
key := d.Val()
switch key {
case "load_owasp_crs":
if d.NextArg() {
return d.ArgErr()
}
m.LoadOWASPCRS = true
case "directives", "include":
var value string
if !d.Args(&value) {
// not enough args
return d.ArgErr()
}
if d.NextArg() {
// too many args
return d.ArgErr()
}
switch key {
case "include":
m.Include = append(m.Include, value)
case "directives":
m.Directives = value
}
default:
return d.Errf("invalid key %q", key)
}
}
return nil
}
// parseCaddyfile unmarshals tokens from h into a new Middleware.
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var m corazaModule
err := m.UnmarshalCaddyfile(h.Dispenser)
return m, err
}
func newErrorCb(logger *zap.Logger) func(types.MatchedRule) {
return func(mr types.MatchedRule) {
logMsg := mr.ErrorLog()
switch mr.Rule().Severity() {
case types.RuleSeverityEmergency,
types.RuleSeverityAlert,
types.RuleSeverityCritical,
types.RuleSeverityError:
logger.Error(logMsg)
case types.RuleSeverityWarning:
logger.Warn(logMsg)
case types.RuleSeverityNotice:
logger.Info(logMsg)
case types.RuleSeverityInfo:
logger.Info(logMsg)
case types.RuleSeverityDebug:
logger.Debug(logMsg)
default:
logger.Warn(logMsg)
}
}
}
// Interface guards
var (
_ caddy.Provisioner = (*corazaModule)(nil)
_ caddy.Validator = (*corazaModule)(nil)
_ caddy.CleanerUpper = (*corazaModule)(nil)
_ caddyhttp.MiddlewareHandler = (*corazaModule)(nil)
_ caddyfile.Unmarshaler = (*corazaModule)(nil)
)