-
Notifications
You must be signed in to change notification settings - Fork 28
/
modsecurity.go
147 lines (127 loc) · 3.74 KB
/
modsecurity.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
// Package traefik_modsecurity_plugin a modsecurity plugin.
package traefik_modsecurity_plugin
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
// Config the plugin configuration.
type Config struct {
TimeoutMillis int64 `json:"timeoutMillis"`
ModSecurityUrl string `json:"modSecurityUrl,omitempty"`
MaxBodySize int64 `json:"maxBodySize"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{
TimeoutMillis: 2000,
// Safe default: if the max body size was not specified, use 10MB
// Note that this will break any file upload with files > 10MB. Hopefully
// the user will configure this parameter during the installation.
MaxBodySize: 10 * 1024 * 1024,
}
}
// Modsecurity a Modsecurity plugin.
type Modsecurity struct {
next http.Handler
modSecurityUrl string
maxBodySize int64
name string
httpClient *http.Client
logger *log.Logger
}
// New created a new Modsecurity plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.ModSecurityUrl) == 0 {
return nil, fmt.Errorf("modSecurityUrl cannot be empty")
}
// Use a custom client with predefined timeout ot 2 seconds
var timeout time.Duration
if config.TimeoutMillis == 0 {
timeout = 2 * time.Second
} else {
timeout = time.Duration(config.TimeoutMillis) * time.Millisecond
}
return &Modsecurity{
modSecurityUrl: config.ModSecurityUrl,
maxBodySize: config.MaxBodySize,
next: next,
name: name,
httpClient: &http.Client{Timeout: timeout},
logger: log.New(os.Stdout, "", log.LstdFlags),
}, nil
}
func (a *Modsecurity) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Websocket not supported
if isWebsocket(req) {
a.next.ServeHTTP(rw, req)
return
}
// we need to buffer the body if we want to read it here and send it
// in the request.
body, err := ioutil.ReadAll(http.MaxBytesReader(rw, req.Body, a.maxBodySize))
if err != nil {
if err.Error() == "http: request body too large" {
a.logger.Printf("body max limit reached: %s", err.Error())
http.Error(rw, "", http.StatusRequestEntityTooLarge)
} else {
a.logger.Printf("fail to read incoming request: %s", err.Error())
http.Error(rw, "", http.StatusBadGateway)
}
return
}
// you can reassign the body if you need to parse it as multipart
req.Body = ioutil.NopCloser(bytes.NewReader(body))
// create a new url from the raw RequestURI sent by the client
url := fmt.Sprintf("%s%s", a.modSecurityUrl, req.RequestURI)
proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body))
if err != nil {
a.logger.Printf("fail to prepare forwarded request: %s", err.Error())
http.Error(rw, "", http.StatusBadGateway)
return
}
// We may want to filter some headers, otherwise we could just use a shallow copy
// proxyReq.Header = req.Header
proxyReq.Header = make(http.Header)
for h, val := range req.Header {
proxyReq.Header[h] = val
}
resp, err := a.httpClient.Do(proxyReq)
if err != nil {
a.logger.Printf("fail to send HTTP request to modsec: %s", err.Error())
http.Error(rw, "", http.StatusBadGateway)
return
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
forwardResponse(resp, rw)
return
}
a.next.ServeHTTP(rw, req)
}
func isWebsocket(req *http.Request) bool {
for _, header := range req.Header["Upgrade"] {
if header == "websocket" {
return true
}
}
return false
}
func forwardResponse(resp *http.Response, rw http.ResponseWriter) {
// copy headers
for k, vv := range resp.Header {
for _, v := range vv {
rw.Header().Set(k, v)
}
}
// copy status
rw.WriteHeader(resp.StatusCode)
// copy body
io.Copy(rw, resp.Body)
}