-
Notifications
You must be signed in to change notification settings - Fork 415
/
actions.go
91 lines (78 loc) · 2.42 KB
/
actions.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
// 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 2022 Datadog, Inc.
//go:build appsec
// +build appsec
package httpsec
import (
"net/http"
)
type action struct {
id string
params ActionParam
}
// ActionHandler handles WAF actions registration and execution
type ActionHandler interface {
RegisterAction(id string, params ActionParam)
Exec(id string, op *Operation)
}
type actionsHandler struct {
actions map[string]action
}
// NewActionsHandler returns an action handler holding the default ASM actions.
// Currently, only the default "block" action is supported
func NewActionsHandler() ActionHandler {
defaultBlockAction := action{
id: "block",
params: BlockRequestParams{
Status: 403,
Template: "html",
},
}
// Register the default "block" action as specified in the RFC for HTTP blocking
actions := map[string]action{defaultBlockAction.id: defaultBlockAction}
return &actionsHandler{
actions: actions,
}
}
// RegisterAction registers a specific action to the actions handler. If the action kind is unknown
// the action will have no effect
func (h *actionsHandler) RegisterAction(id string, params ActionParam) {
h.actions[id] = action{
id: id,
params: params,
}
}
// Exec executes the action identified by `id`
func (h *actionsHandler) Exec(id string, op *Operation) {
a, ok := h.actions[id]
if !ok {
return
}
// Currently, only the "block_request" type is supported, so we only need to check for blockRequestParams
if p, ok := a.params.(BlockRequestParams); ok {
payload := blockedPayload(&p)
op.handler = http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
writer.Write(payload)
writer.WriteHeader(p.Status)
})
}
}
// ActionParam is used to identify an action parameters data type
type ActionParam interface{}
// BlockRequestParams is the parameter struct used to perform actions of kind ActionBlockRequest
type BlockRequestParams struct {
ActionParam
// Status is the return code to use when blocking the request
Status int
// Template is the payload template to use to write the response (html or json)
Template string
}
func blockedPayload(params *BlockRequestParams) []byte {
payload := BlockedTemplateJSON
if params.Template == "html" {
payload = BlockedTemplateHTML
}
return payload
}