-
Notifications
You must be signed in to change notification settings - Fork 415
/
http.go
351 lines (304 loc) · 12.2 KB
/
http.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
// 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.
// Package httpsec defines is the HTTP instrumentation API and contract for
// AppSec. It defines an abstract representation of HTTP handlers, along with
// helper functions to wrap (aka. instrument) standard net/http handlers.
// HTTP integrations must use this package to enable AppSec features for HTTP,
// which listens to this package's operation events.
package httpsec
import (
"context"
// Blank import needed to use embed for the default blocked response payloads
_ "embed"
"encoding/json"
"net"
"net/http"
"os"
"reflect"
"strings"
"sync"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"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"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
)
// Abstract HTTP handler operation definition.
type (
// HandlerOperationArgs is the HTTP handler operation arguments.
HandlerOperationArgs struct {
// RequestURI corresponds to the address `server.request.uri.raw`
RequestURI string
// Headers corresponds to the address `server.request.headers.no_cookies`
Headers map[string][]string
// Cookies corresponds to the address `server.request.cookies`
Cookies map[string][]string
// Query corresponds to the address `server.request.query`
Query map[string][]string
// PathParams corresponds to the address `server.request.path_params`
PathParams map[string]string
// ClientIP corresponds to the addres `http.client_ip`
ClientIP instrumentation.NetaddrIP
}
// HandlerOperationRes is the HTTP handler operation results.
HandlerOperationRes struct {
// Status corresponds to the address `server.response.status`.
Status int
}
// SDKBodyOperationArgs is the SDK body operation arguments.
SDKBodyOperationArgs struct {
// Body corresponds to the address `server.request.body`.
Body interface{}
}
// SDKBodyOperationRes is the SDK body operation results.
SDKBodyOperationRes struct{}
)
// MonitorParsedBody starts and finishes the SDK body operation.
// This function should not be called when AppSec is disabled in order to
// get preciser error logs.
func MonitorParsedBody(ctx context.Context, body interface{}) {
if parent := fromContext(ctx); parent != nil {
op := StartSDKBodyOperation(parent, SDKBodyOperationArgs{Body: body})
op.Finish()
} else {
log.Error("appsec: parsed http body monitoring ignored: could not find the http handler instrumentation metadata in the request context: the request handler is not being monitored by a middleware function or the provided context is not the expected request context")
}
}
// applyActions executes the operation's actions and returns the resulting http handler
func applyActions(op *Operation) http.Handler {
defer op.ClearActions()
for _, action := range op.Actions() {
switch a := action.(type) {
case *BlockRequestAction:
op.AddTag(tagBlockedRequest, true)
return a.handler
default:
log.Error("appsec: ignoring security action: unexpected action type %T", a)
}
}
return nil
}
// WrapHandler wraps the given HTTP handler with the abstract HTTP operation defined by HandlerOperationArgs and
// HandlerOperationRes.
func WrapHandler(handler http.Handler, span ddtrace.Span, pathParams map[string]string) http.Handler {
instrumentation.SetAppSecEnabledTags(span)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
SetIPTags(span, r)
args := MakeHandlerOperationArgs(r, pathParams)
ctx, op := StartOperation(r.Context(), args)
r = r.WithContext(ctx)
if h := applyActions(op); h != nil {
handler = h
}
defer func() {
var status int
if mw, ok := w.(interface{ Status() int }); ok {
status = mw.Status()
}
events := op.Finish(HandlerOperationRes{Status: status})
instrumentation.SetTags(span, op.Tags())
if len(events) == 0 {
return
}
applyActions(op)
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
remoteIP = r.RemoteAddr
}
SetSecurityEventTags(span, events, remoteIP, args.Headers, w.Header())
}()
handler.ServeHTTP(w, r)
})
}
// MakeHandlerOperationArgs creates the HandlerOperationArgs out of a standard
// http.Request along with the given current span. It returns an empty structure
// when appsec is disabled.
func MakeHandlerOperationArgs(r *http.Request, pathParams map[string]string) HandlerOperationArgs {
headers := make(http.Header, len(r.Header))
for k, v := range r.Header {
k := strings.ToLower(k)
if k == "cookie" {
// Do not include cookies in the request headers
continue
}
headers[k] = v
}
cookies := makeCookies(r) // TODO(Julio-Guerra): avoid actively parsing the cookies thanks to dynamic instrumentation
headers["host"] = []string{r.Host}
ip := IPFromHeaders(r.Header, r.RemoteAddr)
log.Debug("FOR THE WAF: %s", ip.String())
return HandlerOperationArgs{
RequestURI: r.RequestURI,
Headers: headers,
Cookies: cookies,
Query: r.URL.Query(), // TODO(Julio-Guerra): avoid actively parsing the query values thanks to dynamic instrumentation
PathParams: pathParams,
ClientIP: ip,
}
}
// Return the map of parsed cookies if any and following the specification of
// the rule address `server.request.cookies`.
func makeCookies(r *http.Request) map[string][]string {
parsed := r.Cookies()
if len(parsed) == 0 {
return nil
}
cookies := make(map[string][]string, len(parsed))
for _, c := range parsed {
cookies[c.Name] = append(cookies[c.Name], c.Value)
}
return cookies
}
// TODO(Julio-Guerra): create a go-generate tool to generate the types, vars and methods below
// Operation type representing an HTTP operation. It must be created with
// StartOperation() and finished with its Finish().
type (
Operation struct {
dyngo.Operation
instrumentation.TagsHolder
instrumentation.SecurityEventsHolder
mu sync.RWMutex
actions []Action
}
// SDKBodyOperation type representing an SDK body. It must be created with
// StartSDKBodyOperation() and finished with its Finish() method.
SDKBodyOperation struct {
dyngo.Operation
}
contextKey struct{}
)
// StartOperation starts an HTTP handler operation, along with the given
// context and arguments and emits a start event up in the operation stack.
// The operation is linked to the global root operation since an HTTP operation
// is always expected to be first in the operation stack.
func StartOperation(ctx context.Context, args HandlerOperationArgs) (context.Context, *Operation) {
op := &Operation{
Operation: dyngo.NewOperation(nil),
TagsHolder: instrumentation.NewTagsHolder(),
}
newCtx := context.WithValue(ctx, contextKey{}, op)
dyngo.StartOperation(op, args)
return newCtx, op
}
func fromContext(ctx context.Context) *Operation {
// Avoid a runtime panic in case of type-assertion error by collecting the 2 return values
op, _ := ctx.Value(contextKey{}).(*Operation)
return op
}
// Finish the HTTP handler operation, along with the given results and emits a
// finish event up in the operation stack.
func (op *Operation) Finish(res HandlerOperationRes) []json.RawMessage {
dyngo.FinishOperation(op, res)
return op.Events()
}
// Actions returns the actions linked to the operation
func (op *Operation) Actions() []Action {
op.mu.RLock()
defer op.mu.RUnlock()
return op.actions
}
// AddAction adds an action to the operation
func (op *Operation) AddAction(a Action) {
op.mu.Lock()
defer op.mu.Unlock()
op.actions = append(op.actions, a)
}
// ClearActions clears all the actions linked to the operation
func (op *Operation) ClearActions() {
op.mu.Lock()
defer op.mu.Unlock()
op.actions = op.actions[0:0]
}
// StartSDKBodyOperation starts the SDKBody operation and emits a start event
func StartSDKBodyOperation(parent *Operation, args SDKBodyOperationArgs) *SDKBodyOperation {
op := &SDKBodyOperation{Operation: dyngo.NewOperation(parent)}
dyngo.StartOperation(op, args)
return op
}
// Finish finishes the SDKBody operation and emits a finish event
func (op *SDKBodyOperation) Finish() {
dyngo.FinishOperation(op, SDKBodyOperationRes{})
}
// HTTP handler operation's start and finish event callback function types.
type (
// OnHandlerOperationStart function type, called when an HTTP handler
// operation starts.
OnHandlerOperationStart func(*Operation, HandlerOperationArgs)
// OnHandlerOperationFinish function type, called when an HTTP handler
// operation finishes.
OnHandlerOperationFinish func(*Operation, HandlerOperationRes)
// OnSDKBodyOperationStart function type, called when an SDK body
// operation starts.
OnSDKBodyOperationStart func(*SDKBodyOperation, SDKBodyOperationArgs)
// OnSDKBodyOperationFinish function type, called when an SDK body
// operation finishes.
OnSDKBodyOperationFinish func(*SDKBodyOperation, SDKBodyOperationRes)
)
var (
handlerOperationArgsType = reflect.TypeOf((*HandlerOperationArgs)(nil)).Elem()
handlerOperationResType = reflect.TypeOf((*HandlerOperationRes)(nil)).Elem()
sdkBodyOperationArgsType = reflect.TypeOf((*SDKBodyOperationArgs)(nil)).Elem()
sdkBodyOperationResType = reflect.TypeOf((*SDKBodyOperationRes)(nil)).Elem()
)
// ListenedType returns the type a OnHandlerOperationStart event listener
// listens to, which is the HandlerOperationArgs type.
func (OnHandlerOperationStart) ListenedType() reflect.Type { return handlerOperationArgsType }
// Call calls the underlying event listener function by performing the
// type-assertion on v whose type is the one returned by ListenedType().
func (f OnHandlerOperationStart) Call(op dyngo.Operation, v interface{}) {
f(op.(*Operation), v.(HandlerOperationArgs))
}
// ListenedType returns the type a OnHandlerOperationFinish event listener
// listens to, which is the HandlerOperationRes type.
func (OnHandlerOperationFinish) ListenedType() reflect.Type { return handlerOperationResType }
// Call calls the underlying event listener function by performing the
// type-assertion on v whose type is the one returned by ListenedType().
func (f OnHandlerOperationFinish) Call(op dyngo.Operation, v interface{}) {
f(op.(*Operation), v.(HandlerOperationRes))
}
// ListenedType returns the type a OnSDKBodyOperationStart event listener
// listens to, which is the SDKBodyOperationStartArgs type.
func (OnSDKBodyOperationStart) ListenedType() reflect.Type { return sdkBodyOperationArgsType }
// Call calls the underlying event listener function by performing the
// type-assertion on v whose type is the one returned by ListenedType().
func (f OnSDKBodyOperationStart) Call(op dyngo.Operation, v interface{}) {
f(op.(*SDKBodyOperation), v.(SDKBodyOperationArgs))
}
// ListenedType returns the type a OnSDKBodyOperationFinish event listener
// listens to, which is the SDKBodyOperationRes type.
func (OnSDKBodyOperationFinish) ListenedType() reflect.Type { return sdkBodyOperationResType }
// Call calls the underlying event listener function by performing the
// type-assertion on v whose type is the one returned by ListenedType().
func (f OnSDKBodyOperationFinish) Call(op dyngo.Operation, v interface{}) {
f(op.(*SDKBodyOperation), v.(SDKBodyOperationRes))
}
// IPFromHeaders tries to resolve and return the user IP from request headers
func IPFromHeaders(hdrs map[string][]string, remoteAddr string) instrumentation.NetaddrIP {
ip := IPTagsFromHeaders(hdrs, remoteAddr)[ext.HTTPClientIP]
return parseIP(ip)
}
// blockedTemplateJSON is the default JSON template used to write responses for blocked requests
//
//go:embed blocked-template.json
var blockedTemplateJSON []byte
// blockedTemplateHTML is the default HTML template used to write responses for blocked requests
//
//go:embed blocked-template.html
var blockedTemplateHTML []byte
const (
envBlockedTemplateHTML = "DD_APPSEC_HTTP_BLOCKED_TEMPLATE_HTML"
envBlockedTemplateJSON = "DD_APPSEC_HTTP_BLOCKED_TEMPLATE_JSON"
)
func init() {
for env, template := range map[string]*[]byte{envBlockedTemplateJSON: &blockedTemplateJSON, envBlockedTemplateHTML: &blockedTemplateHTML} {
if path, ok := os.LookupEnv(env); ok {
if t, err := os.ReadFile(path); err != nil {
log.Warn("Could not read template at %s: %v", path, err)
} else {
*template = t
}
}
}
}