-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.go
328 lines (270 loc) · 8.25 KB
/
main.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright 2022 The OWASP Coraza contributors
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"embed"
"fmt"
"io/fs"
"strconv"
"github.com/corazawaf/coraza/v3"
"github.com/corazawaf/coraza/v3/seclang"
ctypes "github.com/corazawaf/coraza/v3/types"
"github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm"
"github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/types"
"github.com/tidwall/gjson"
)
//go:embed custom_rules
var crs embed.FS
func main() {
proxywasm.SetVMContext(&vmContext{})
}
type vmContext struct {
// Embed the default VM context here,
// so that we don't need to reimplement all the methods.
types.DefaultVMContext
}
// Override types.DefaultVMContext.
func (*vmContext) NewPluginContext(contextID uint32) types.PluginContext {
return &corazaPlugin{}
}
type corazaPlugin struct {
// Embed the default plugin context here,
// so that we don't need to reimplement all the methods.
types.DefaultPluginContext
waf *coraza.Waf
}
// pluginConfiguration is a type to represent an example configuration for this wasm plugin.
type pluginConfiguration struct {
rules string
includeCRS bool
}
// Override types.DefaultPluginContext.
func (ctx *corazaPlugin) OnPluginStart(pluginConfigurationSize int) types.OnPluginStartStatus {
data, err := proxywasm.GetPluginConfiguration()
if err != nil && err != types.ErrorStatusNotFound {
proxywasm.LogCriticalf("error reading plugin configuration: %v", err)
return types.OnPluginStartStatusFailed
}
config, err := parsePluginConfiguration(data)
if err != nil {
proxywasm.LogCriticalf("error parsing plugin configuration: %v", err)
return types.OnPluginStartStatusFailed
}
// First we initialize our waf and our seclang parser
waf := coraza.NewWaf()
waf.SetErrorLogCb(logError)
waf.Logger = &debugLogger{}
// TinyGo compilation will prevent buffering request body to files anyways, so this is
// effectively no-op but make clear our expectations.
// TODO(anuraaga): Make this configurable in plugin configuration.
waf.RequestBodyLimit = waf.RequestBodyInMemoryLimit
parser, err := seclang.NewParser(waf)
if err != nil {
proxywasm.LogCriticalf("failed to create seclang parser: %v", err)
return types.OnPluginStartStatusFailed
}
err = parser.FromString(config.rules)
if err != nil {
proxywasm.LogCriticalf("failed to parse rules: %v", err)
return types.OnPluginStartStatusFailed
}
if config.includeCRS {
err = fs.WalkDir(crs, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
f, _ := crs.ReadFile(path)
if err := parser.FromString(string(f)); err != nil {
return fmt.Errorf("%s: %v", path, err)
}
return nil
})
if err != nil {
proxywasm.LogCriticalf("failed to parse core rule set: %v", err)
return types.OnPluginStartStatusFailed
}
}
ctx.waf = waf
return types.OnPluginStartStatusOK
}
func parsePluginConfiguration(data []byte) (pluginConfiguration, error) {
config := pluginConfiguration{
includeCRS: true,
}
if len(data) == 0 {
return config, nil
}
if !gjson.ValidBytes(data) {
return pluginConfiguration{}, fmt.Errorf("invalid json: %q", string(data))
}
jsonData := gjson.ParseBytes(data)
rules := jsonData.Get("rules")
if rules.Exists() {
config.rules = rules.String()
}
includeCRS := jsonData.Get("include_core_rule_set")
if includeCRS.Exists() && !includeCRS.Bool() {
config.includeCRS = false
}
return config, nil
}
// Override types.DefaultPluginContext.
func (ctx *corazaPlugin) NewHttpContext(contextID uint32) types.HttpContext {
return &httpContext{contextID: contextID, tx: ctx.waf.NewTransaction(context.Background())}
}
type httpContext struct {
// Embed the default http context here,
// so that we don't need to reimplement all the methods.
types.DefaultHttpContext
contextID uint32
tx *coraza.Transaction
}
// Override types.DefaultHttpContext.
func (ctx *httpContext) OnHttpRequestHeaders(numHeaders int, endOfStream bool) types.Action {
tx := ctx.tx
// TODO(anuraaga): Do these work with HTTP/1?
path, err := proxywasm.GetHttpRequestHeader(":path")
if err != nil {
proxywasm.LogCriticalf("failed to get :path: %v", err)
return types.ActionContinue
}
method, err := proxywasm.GetHttpRequestHeader(":method")
if err != nil {
proxywasm.LogCriticalf("failed to get :method: %v", err)
return types.ActionContinue
}
tx.ProcessURI(path, method, "HTTP/2.0") // TODO use the right HTTP version
hs, err := proxywasm.GetHttpRequestHeaders()
if err != nil {
proxywasm.LogCriticalf("failed to get request headers: %v", err)
return types.ActionContinue
}
for _, h := range hs {
tx.AddRequestHeader(h[0], h[1])
}
interruption := tx.ProcessRequestHeaders()
if interruption != nil {
return ctx.handleInterruption(interruption)
}
return types.ActionContinue
}
func (ctx *httpContext) OnHttpRequestBody(bodySize int, endOfStream bool) types.Action {
tx := ctx.tx
if bodySize > 0 {
body, err := proxywasm.GetHttpRequestBody(0, bodySize)
if err != nil {
proxywasm.LogCriticalf("failed to get request body: %v", err)
return types.ActionContinue
}
_, err = tx.RequestBodyBuffer.Write(body)
if err != nil {
proxywasm.LogCriticalf("failed to read request body: %v", err)
return types.ActionContinue
}
}
if !endOfStream {
return types.ActionContinue
}
interruption, err := tx.ProcessRequestBody()
if err != nil {
proxywasm.LogCriticalf("failed to process request body: %v", err)
return types.ActionContinue
}
if interruption != nil {
return ctx.handleInterruption(interruption)
}
return types.ActionContinue
}
func (ctx *httpContext) OnHttpResponseHeaders(numHeaders int, endOfStream bool) types.Action {
tx := ctx.tx
status, err := proxywasm.GetHttpResponseHeader(":status")
if err != nil {
proxywasm.LogCriticalf("failed to get :status: %v", err)
return types.ActionContinue
}
code, err := strconv.Atoi(status)
if err != nil {
code = 0
}
hs, err := proxywasm.GetHttpResponseHeaders()
if err != nil {
proxywasm.LogCriticalf("failed to get response headers: %v", err)
return types.ActionContinue
}
for _, h := range hs {
tx.AddResponseHeader(h[0], h[1])
}
interruption := tx.ProcessResponseHeaders(code, "HTTP/2.0")
if interruption != nil {
return ctx.handleInterruption(interruption)
}
return types.ActionContinue
}
func (ctx *httpContext) OnHttpResponseBody(bodySize int, endOfStream bool) types.Action {
tx := ctx.tx
if bodySize > 0 {
body, err := proxywasm.GetHttpResponseBody(0, bodySize)
if err != nil {
proxywasm.LogCriticalf("failed to get response body: %v", err)
return types.ActionContinue
}
_, err = tx.ResponseBodyBuffer.Write(body)
if err != nil {
proxywasm.LogCriticalf("failed to read response body: %v", err)
return types.ActionContinue
}
}
if !endOfStream {
return types.ActionContinue
}
// We have already sent response headers so cannot now send an unauthorized response.
// The error will have been logged by Coraza though.
_, err := tx.ProcessResponseBody()
if err != nil {
proxywasm.LogCriticalf("failed to process response body: %v", err)
return types.ActionContinue
}
return types.ActionContinue
}
// Override types.DefaultHttpContext.
func (ctx *httpContext) OnHttpStreamDone() {
ctx.tx.ProcessLogging()
_ = ctx.tx.Clean()
proxywasm.LogInfof("%d finished", ctx.contextID)
}
func (ctx *httpContext) handleInterruption(interruption *ctypes.Interruption) types.Action {
proxywasm.LogInfof("%d interrupted, action %q", ctx.contextID, interruption.Action)
statusCode := interruption.Status
if statusCode == 0 {
statusCode = 403
}
if err := proxywasm.SendHttpResponse(uint32(statusCode), nil, nil, -1); err != nil {
panic(err)
}
return types.ActionPause
}
func logError(error ctypes.MatchedRule) {
msg := error.ErrorLog(0)
switch error.Rule.Severity {
case ctypes.RuleSeverityEmergency:
proxywasm.LogCritical(msg)
case ctypes.RuleSeverityAlert:
proxywasm.LogCritical(msg)
case ctypes.RuleSeverityCritical:
proxywasm.LogCritical(msg)
case ctypes.RuleSeverityError:
proxywasm.LogError(msg)
case ctypes.RuleSeverityWarning:
proxywasm.LogWarn(msg)
case ctypes.RuleSeverityNotice:
proxywasm.LogInfo(msg)
case ctypes.RuleSeverityInfo:
proxywasm.LogInfo(msg)
case ctypes.RuleSeverityDebug:
proxywasm.LogDebug(msg)
}
}