-
Notifications
You must be signed in to change notification settings - Fork 52
/
modsec.go
293 lines (244 loc) · 9.25 KB
/
modsec.go
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
package mid
import (
"bytes"
"fmt"
"io"
"net"
"strconv"
"strings"
"github.com/corazawaf/coraza/v3"
"github.com/corazawaf/coraza/v3/experimental"
"github.com/corazawaf/coraza/v3/types"
"github.com/pkg/errors"
utils "github.com/savsgio/gotils/strconv"
"github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
"github.com/wallarm/api-firewall/internal/platform/router"
"github.com/wallarm/api-firewall/internal/platform/web"
"github.com/wallarm/api-firewall/pkg/APIMode/validator"
)
type ModSecurityOptions struct {
Mode string
WAF coraza.WAF
Logger *logrus.Logger
RequestValidation string
ResponseValidation string
CustomBlockStatusCode int
}
var ErrModSecMaliciousRequest = errors.New("malicious request")
// processRequest fills all transaction variables from an http.Request object
// Most implementations of Coraza will probably use http.Request objects
// so this will implement all phase 0, 1 and 2 variables
// Note: This function will stop after an interruption
// Note: Do not manually fill any request variables
func processRequest(tx types.Transaction, ctx *fasthttp.RequestCtx) (*types.Interruption, error) {
var (
client string
cport int
)
// IMPORTANT: Some http.Request.RemoteAddr implementations will not contain port or contain IPV6: [2001:db8::1]:8080
client, cportStr, err := net.SplitHostPort(ctx.RemoteAddr().String())
if err != nil {
return nil, err
}
cport, _ = strconv.Atoi(cportStr)
var in *types.Interruption
// There is no socket access in the request object, so we neither know the server client nor port.
tx.ProcessConnection(client, cport, "", 0)
//tx.ProcessURI(req.URL.String(), req.Method, req.Proto)
rUri := ctx.Request.URI().String()
tx.ProcessURI(rUri, utils.B2S(ctx.Request.Header.Method()), utils.B2S(ctx.Request.Header.Protocol()))
ctx.Request.Header.VisitAll(func(k, v []byte) {
tx.AddRequestHeader(utils.B2S(k), utils.B2S(v))
})
// Host will always be removed from req.Headers() and promoted to the
// Request.Host field, so we manually add it
if host := utils.B2S(ctx.Request.Host()); host != "" {
tx.AddRequestHeader("Host", host)
// This connector relies on the host header (now host field) to populate ServerName
tx.SetServerName(host)
}
// Transfer-Encoding header is removed by go/http
// We manually add it to make rules relying on it work (E.g. CRS rule 920171)
if te := ctx.Request.Header.Peek(fasthttp.HeaderTransferEncoding); te != nil {
tx.AddRequestHeader("Transfer-Encoding", utils.B2S(te))
}
in = tx.ProcessRequestHeaders()
if in != nil {
return in, nil
}
if tx.IsRequestBodyAccessible() {
// We only do body buffering if the transaction requires request
// body inspection, otherwise we just let the request follow its
// regular flow.
bodyRaw := ctx.Request.Body()
bodyReader := io.NopCloser(bytes.NewReader(bodyRaw))
if bodyRaw != nil {
it, _, err := tx.ReadRequestBodyFrom(bodyReader)
if err != nil {
return nil, fmt.Errorf("failed to append request body: %s", err.Error())
}
if it != nil {
return it, nil
}
}
}
return tx.ProcessRequestBody()
}
func WAFModSecurity(options *ModSecurityOptions) web.Middleware {
// This is the actual middleware function to be executed.
m := func(before router.Handler) router.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx *fasthttp.RequestCtx) error {
if options.WAF == nil {
err := before(ctx)
// Return the error, so it can be handled further up the chain.
return err
}
newTX := func(requestCtx *fasthttp.RequestCtx) types.Transaction {
return options.WAF.NewTransaction()
}
if ctxwaf, ok := options.WAF.(experimental.WAFWithOptions); ok {
newTX = func(requestCtx *fasthttp.RequestCtx) types.Transaction {
return ctxwaf.NewTransactionWithOptions(experimental.Options{
Context: requestCtx,
})
}
}
tx := newTX(ctx)
defer func() {
// We run phase 5 rules and create audit logs (if enabled)
tx.ProcessLogging()
// we remove temporary files and free some memory
if err := tx.Close(); err != nil {
tx.DebugLogger().Error().Err(err).Msg("Failed to close the transaction")
}
}()
// Early return, Coraza is not going to process any rule
if tx.IsRuleEngineOff() {
return nil
}
if !strings.EqualFold(options.RequestValidation, web.ValidationDisable) {
// 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, ctx); err != nil {
tx.DebugLogger().Error().Err(err).Msg("Failed to process request")
if options.Mode == web.APIMode {
if err := respondAPIModeErrors(ctx, "ModSecurity rules: failed to process request", err.Error()); err != nil {
options.Logger.WithFields(logrus.Fields{
"host": utils.B2S(ctx.Request.Header.Host()),
"path": utils.B2S(ctx.Path()),
"method": utils.B2S(ctx.Request.Header.Method()),
"request_id": ctx.UserValue(web.RequestID),
}).Error(err)
}
return nil
}
if strings.EqualFold(options.RequestValidation, web.ValidationBlock) {
return err
}
} else if it != nil {
if options.Mode == web.APIMode {
if err := respondAPIModeErrors(ctx, ErrModSecMaliciousRequest.Error(), fmt.Sprintf("ModSecurity rules: request blocked due to rule %d", it.RuleID)); err != nil {
options.Logger.WithFields(logrus.Fields{
"host": utils.B2S(ctx.Request.Header.Host()),
"path": utils.B2S(ctx.Path()),
"method": utils.B2S(ctx.Request.Header.Method()),
"request_id": ctx.UserValue(web.RequestID),
}).Error(err)
}
return nil
}
if strings.EqualFold(options.RequestValidation, web.ValidationBlock) {
return performResponseAction(ctx, it, options.CustomBlockStatusCode)
}
}
}
// Run the handler chain and catch any propagated error.
if err := before(ctx); err != nil {
return err
}
// do not check response in the API mode
if options.Mode == web.APIMode {
return nil
}
if !strings.EqualFold(options.ResponseValidation, web.ValidationDisable) {
ctx.Response.Header.VisitAll(func(k, v []byte) {
tx.AddResponseHeader(utils.B2S(k), utils.B2S(v))
})
if it := tx.ProcessResponseHeaders(ctx.Response.StatusCode(), utils.B2S(ctx.Request.Header.Protocol())); it != nil {
if strings.EqualFold(options.ResponseValidation, web.ValidationBlock) {
return performResponseAction(ctx, it, options.CustomBlockStatusCode)
}
}
if tx.IsResponseBodyAccessible() && tx.IsResponseBodyProcessable() {
// read response body
bodyRaw := ctx.Response.Body()
bodyReader := io.NopCloser(bytes.NewReader(bodyRaw))
if bodyRaw != nil {
it, _, err := tx.ReadResponseBodyFrom(bodyReader)
if err != nil {
return fmt.Errorf("failed to append request body: %s", err.Error())
}
if it != nil {
if strings.EqualFold(options.ResponseValidation, web.ValidationBlock) {
return performResponseAction(ctx, it, options.CustomBlockStatusCode)
}
}
}
if it, err := tx.ProcessResponseBody(); err != nil {
tx.DebugLogger().Error().Err(err).Msg("Failed to process response")
if strings.EqualFold(options.ResponseValidation, web.ValidationBlock) {
return err
}
} else if it != nil {
if strings.EqualFold(options.ResponseValidation, web.ValidationBlock) {
return performResponseAction(ctx, it, options.CustomBlockStatusCode)
}
}
}
}
// The error has been handled so we can stop propagating it.
return nil
}
return h
}
return m
}
// obtainStatusCodeFromInterruptionOrDefault returns the desired status code derived from the interruption
// on a "deny" action or a default value.
func performResponseAction(ctx *fasthttp.RequestCtx, it *types.Interruption, blockStatusCode int) error {
switch it.Action {
case "deny", "drop":
statusCode := it.Status
if statusCode == 0 {
statusCode = blockStatusCode
}
ctx.Response.Header.SetContentLength(0)
return web.RespondError(ctx, statusCode, "")
case "redirect":
ctx.Response.Header.SetContentLength(0)
ctx.Redirect(it.Data, it.Status)
return nil
}
return nil
}
// respondAPIModeErrors sends API mode specific response back to the client
func respondAPIModeErrors(ctx *fasthttp.RequestCtx, code, message string) error {
schemaIDstr, ok := ctx.UserValue(web.RequestSchemaID).(string)
if !ok {
ctx.SetUserValue(web.GlobalResponseStatusCodeKey, fasthttp.StatusInternalServerError)
return errors.New("request schema ID not found in the request")
}
schemaID, err := strconv.Atoi(schemaIDstr)
if err != nil {
ctx.SetUserValue(web.GlobalResponseStatusCodeKey, fasthttp.StatusInternalServerError)
return err
}
keyValidationErrors := schemaIDstr + validator.APIModePostfixValidationErrors
keyStatusCode := schemaIDstr + validator.APIModePostfixStatusCode
ctx.SetUserValue(keyValidationErrors, []*validator.ValidationError{{Message: message, Code: code, SchemaID: &schemaID}})
ctx.SetUserValue(keyStatusCode, fasthttp.StatusForbidden)
return nil
}