-
Notifications
You must be signed in to change notification settings - Fork 415
/
waf.go
360 lines (322 loc) · 12.7 KB
/
waf.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
//go:build appsec
// +build appsec
package appsec
import (
"encoding/json"
"errors"
"fmt"
"sort"
"sync"
"sync/atomic"
"time"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/internal/appsec/dyngo"
"gopkg.in/DataDog/dd-trace-go.v1/internal/appsec/dyngo/instrumentation/grpcsec"
"gopkg.in/DataDog/dd-trace-go.v1/internal/appsec/dyngo/instrumentation/httpsec"
"gopkg.in/DataDog/dd-trace-go.v1/internal/appsec/waf"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
"gopkg.in/DataDog/dd-trace-go.v1/internal/samplernames"
)
const (
eventRulesVersionTag = "_dd.appsec.event_rules.version"
eventRulesErrorsTag = "_dd.appsec.event_rules.errors"
eventRulesLoadedTag = "_dd.appsec.event_rules.loaded"
eventRulesFailedTag = "_dd.appsec.event_rules.error_count"
wafDurationTag = "_dd.appsec.waf.duration"
wafDurationExtTag = "_dd.appsec.waf.duration_ext"
wafTimeoutTag = "_dd.appsec.waf.timeouts"
wafVersionTag = "_dd.appsec.waf.version"
)
// Register the WAF event listener.
func registerWAF(rules []byte, timeout time.Duration, limiter Limiter, obfCfg *ObfuscatorConfig) (unreg dyngo.UnregisterFunc, err error) {
// Check the WAF is healthy
if err := waf.Health(); err != nil {
return nil, err
}
// Instantiate the WAF
waf, err := waf.NewHandle(rules, obfCfg.KeyRegex, obfCfg.ValueRegex)
if err != nil {
return nil, err
}
// Close the WAF in case of an error in what's following
defer func() {
if err != nil {
waf.Close()
}
}()
// Check if there are addresses in the rule
ruleAddresses := waf.Addresses()
if len(ruleAddresses) == 0 {
return nil, errors.New("no addresses found in the rule")
}
// Check there are supported addresses in the rule
httpAddresses, grpcAddresses, notSupported := supportedAddresses(ruleAddresses)
if len(httpAddresses) == 0 && len(grpcAddresses) == 0 {
return nil, fmt.Errorf("the addresses present in the rule are not supported: %v", notSupported)
} else if len(notSupported) > 0 {
log.Debug("appsec: the addresses present in the rule are partially supported: not supported=%v", notSupported)
}
// Register the WAF event listener
var unregisterHTTP, unregisterGRPC dyngo.UnregisterFunc
if len(httpAddresses) > 0 {
log.Debug("appsec: registering http waf listening to addresses %v", httpAddresses)
unregisterHTTP = dyngo.Register(newHTTPWAFEventListener(waf, httpAddresses, timeout, limiter))
}
if len(grpcAddresses) > 0 {
log.Debug("appsec: registering grpc waf listening to addresses %v", grpcAddresses)
unregisterGRPC = dyngo.Register(newGRPCWAFEventListener(waf, grpcAddresses, timeout, limiter))
}
// Return an unregistration function that will also release the WAF instance.
return func() {
defer waf.Close()
if unregisterHTTP != nil {
unregisterHTTP()
}
if unregisterGRPC != nil {
unregisterGRPC()
}
}, nil
}
// newWAFEventListener returns the WAF event listener to register in order to enable it.
func newHTTPWAFEventListener(handle *waf.Handle, addresses []string, timeout time.Duration, limiter Limiter) dyngo.EventListener {
var monitorRulesOnce sync.Once // per instantiation
return httpsec.OnHandlerOperationStart(func(op *httpsec.Operation, args httpsec.HandlerOperationArgs) {
var body interface{}
op.On(httpsec.OnSDKBodyOperationStart(func(op *httpsec.SDKBodyOperation, args httpsec.SDKBodyOperationArgs) {
body = args.Body
}))
// At the moment, AppSec doesn't block the requests, and so we can use the fact we are in monitoring-only mode
// to call the WAF only once at the end of the handler operation.
op.On(httpsec.OnHandlerOperationFinish(func(op *httpsec.Operation, res httpsec.HandlerOperationRes) {
wafCtx := waf.NewContext(handle)
if wafCtx == nil {
// The WAF event listener got concurrently released
return
}
defer wafCtx.Close()
// Run the WAF on the rule addresses available in the request args
values := make(map[string]interface{}, len(addresses))
for _, addr := range addresses {
switch addr {
case serverRequestRawURIAddr:
values[serverRequestRawURIAddr] = args.RequestURI
case serverRequestHeadersNoCookiesAddr:
if headers := args.Headers; headers != nil {
values[serverRequestHeadersNoCookiesAddr] = headers
}
case serverRequestCookiesAddr:
if cookies := args.Cookies; cookies != nil {
values[serverRequestCookiesAddr] = cookies
}
case serverRequestQueryAddr:
if query := args.Query; query != nil {
values[serverRequestQueryAddr] = query
}
case serverRequestPathParams:
if pathParams := args.PathParams; pathParams != nil {
values[serverRequestPathParams] = pathParams
}
case serverRequestBody:
if body != nil {
values[serverRequestBody] = body
}
case serverResponseStatusAddr:
values[serverResponseStatusAddr] = res.Status
case httpClientIP:
if args.ClientIP.IsValid() {
values[httpClientIP] = args.ClientIP.String()
}
}
}
matches := runWAF(wafCtx, values, timeout)
// Add WAF metrics.
rInfo := handle.RulesetInfo()
overallRuntimeNs, internalRuntimeNs := wafCtx.TotalRuntime()
addWAFMonitoringTags(op, rInfo.Version, overallRuntimeNs, internalRuntimeNs, wafCtx.TotalTimeouts())
// Add the following metrics once per instantiation of a WAF handle
monitorRulesOnce.Do(func() {
addRulesMonitoringTags(op, rInfo)
op.AddTag(ext.ManualKeep, samplernames.AppSec)
})
// Log the attacks if any
if len(matches) == 0 {
return
}
log.Debug("appsec: attack detected by the waf")
if limiter.Allow() {
op.AddSecurityEvents(matches)
}
}))
})
}
// newGRPCWAFEventListener returns the WAF event listener to register in order
// to enable it.
func newGRPCWAFEventListener(handle *waf.Handle, _ []string, timeout time.Duration, limiter Limiter) dyngo.EventListener {
var monitorRulesOnce sync.Once // per instantiation
return grpcsec.OnHandlerOperationStart(func(op *grpcsec.HandlerOperation, handlerArgs grpcsec.HandlerOperationArgs) {
// Limit the maximum number of security events, as a streaming RPC could
// receive unlimited number of messages where we could find security events
const maxWAFEventsPerRequest = 10
var (
nbEvents uint32
logOnce sync.Once // per request
overallRuntimeNs waf.AtomicU64
internalRuntimeNs waf.AtomicU64
nbTimeouts waf.AtomicU64
events []json.RawMessage
mu sync.Mutex // events mutex
)
op.On(grpcsec.OnReceiveOperationFinish(func(_ grpcsec.ReceiveOperation, res grpcsec.ReceiveOperationRes) {
if atomic.LoadUint32(&nbEvents) == maxWAFEventsPerRequest {
logOnce.Do(func() {
log.Debug("appsec: ignoring the rpc message due to the maximum number of security events per grpc call reached")
})
return
}
// The current workaround of the WAF context limitations is to
// simply instantiate and release the WAF context for the operation
// lifetime so that:
// 1. We avoid growing the memory usage of the context every time
// a grpc.server.request.message value is added to it during
// the RPC lifetime.
// 2. We avoid the limitation of 1 event per attack type.
// TODO(Julio-Guerra): a future libddwaf API should solve this out.
wafCtx := waf.NewContext(handle)
if wafCtx == nil {
// The WAF event listener got concurrently released
return
}
defer wafCtx.Close()
// Run the WAF on the rule addresses available in the args
// Note that we don't check if the address is present in the rules
// as we only support one at the moment, so this callback cannot be
// set when the address is not present.
values := map[string]interface{}{grpcServerRequestMessage: res.Message}
if md := handlerArgs.Metadata; len(md) > 0 {
values[grpcServerRequestMetadata] = md
}
event := runWAF(wafCtx, values, timeout)
// WAF run durations are WAF context bound. As of now we need to keep track of those externally since
// we use a new WAF context for each callback. When we are able to re-use the same WAF context across
// callbacks, we can get rid of these variables and simply use the WAF bindings in OnHandlerOperationFinish.
overall, internal := wafCtx.TotalRuntime()
overallRuntimeNs.Add(overall)
internalRuntimeNs.Add(internal)
nbTimeouts.Add(wafCtx.TotalTimeouts())
if len(event) == 0 {
return
}
log.Debug("appsec: attack detected by the grpc waf")
atomic.AddUint32(&nbEvents, 1)
mu.Lock()
events = append(events, event)
mu.Unlock()
}))
op.On(grpcsec.OnHandlerOperationFinish(func(op *grpcsec.HandlerOperation, _ grpcsec.HandlerOperationRes) {
rInfo := handle.RulesetInfo()
addWAFMonitoringTags(op, rInfo.Version, overallRuntimeNs.Load(), internalRuntimeNs.Load(), nbTimeouts.Load())
// Log the following metrics once per instantiation of a WAF handle
monitorRulesOnce.Do(func() {
addRulesMonitoringTags(op, rInfo)
op.AddTag(ext.ManualKeep, samplernames.AppSec)
})
// Log the events if any
if len(events) > 0 && limiter.Allow() {
op.AddSecurityEvents(events...)
}
}))
})
}
func runWAF(wafCtx *waf.Context, values map[string]interface{}, timeout time.Duration) []byte {
matches, _, err := wafCtx.Run(values, timeout)
if err != nil {
if err == waf.ErrTimeout {
log.Debug("appsec: waf timeout value of %s reached", timeout)
} else {
log.Error("appsec: unexpected waf error: %v", err)
return nil
}
}
return matches
}
// HTTP rule addresses currently supported by the WAF
const (
serverRequestRawURIAddr = "server.request.uri.raw"
serverRequestHeadersNoCookiesAddr = "server.request.headers.no_cookies"
serverRequestCookiesAddr = "server.request.cookies"
serverRequestQueryAddr = "server.request.query"
serverRequestPathParams = "server.request.path_params"
serverRequestBody = "server.request.body"
serverResponseStatusAddr = "server.response.status"
httpClientIP = "http.client_ip"
)
// List of HTTP rule addresses currently supported by the WAF
var httpAddresses = []string{
serverRequestRawURIAddr,
serverRequestHeadersNoCookiesAddr,
serverRequestCookiesAddr,
serverRequestQueryAddr,
serverRequestPathParams,
serverRequestBody,
serverResponseStatusAddr,
httpClientIP,
}
// gRPC rule addresses currently supported by the WAF
const (
grpcServerRequestMessage = "grpc.server.request.message"
grpcServerRequestMetadata = "grpc.server.request.metadata"
)
// List of gRPC rule addresses currently supported by the WAF
var grpcAddresses = []string{
grpcServerRequestMessage,
grpcServerRequestMetadata,
}
func init() {
// sort the address lists to avoid mistakes and use sort.SearchStrings()
sort.Strings(httpAddresses)
sort.Strings(grpcAddresses)
}
// supportedAddresses returns the list of addresses we actually support from the
// given rule addresses.
func supportedAddresses(ruleAddresses []string) (supportedHTTP, supportedGRPC, notSupported []string) {
// Filter the supported addresses only
for _, addr := range ruleAddresses {
if i := sort.SearchStrings(httpAddresses, addr); i < len(httpAddresses) && httpAddresses[i] == addr {
supportedHTTP = append(supportedHTTP, addr)
} else if i := sort.SearchStrings(grpcAddresses, addr); i < len(grpcAddresses) && grpcAddresses[i] == addr {
supportedGRPC = append(supportedGRPC, addr)
} else {
notSupported = append(notSupported, addr)
}
}
return
}
type tagsHolder interface {
AddTag(string, interface{})
}
// Add the tags related to security rules monitoring
func addRulesMonitoringTags(th tagsHolder, rInfo waf.RulesetInfo) {
if len(rInfo.Errors) == 0 {
rInfo.Errors = nil
}
rulesetErrors, err := json.Marshal(rInfo.Errors)
if err != nil {
log.Error("appsec: could not marshal ruleset info errors to json")
}
th.AddTag(eventRulesErrorsTag, string(rulesetErrors)) // avoid the tracer's call to fmt.Sprintf on the value
th.AddTag(eventRulesLoadedTag, float64(rInfo.Loaded))
th.AddTag(eventRulesFailedTag, float64(rInfo.Failed))
th.AddTag(wafVersionTag, waf.Version())
}
// Add the tags related to the monitoring of the WAF
func addWAFMonitoringTags(th tagsHolder, rulesVersion string, overallRuntimeNs, internalRuntimeNs, timeouts uint64) {
// Rules version is set for every request to help the backend associate WAF duration metrics with rule version
th.AddTag(eventRulesVersionTag, rulesVersion)
th.AddTag(wafTimeoutTag, float64(timeouts))
th.AddTag(wafDurationTag, float64(internalRuntimeNs)/1e3) // ns to us
th.AddTag(wafDurationExtTag, float64(overallRuntimeNs)/1e3) // ns to us
}