forked from EOSIO/patroneos
-
Notifications
You must be signed in to change notification settings - Fork 2
/
filter.go
385 lines (322 loc) · 9.98 KB
/
filter.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
// Middleware returns a handler that can perform various operations
// and calls the next HTTP handler as the final action.
type middleware func(next http.HandlerFunc) http.HandlerFunc
// ErrorMessage defines the structure of an error response
type ErrorMessage struct {
Message string `json:"message"`
Code int `json:"code"`
}
// Action represents the structure of an action rpc payload
type Action struct {
Code string `json:"code"`
Data string `json:"data"`
}
// Transaction describes the structure of a transaction rpc payload
type Transaction struct {
Actions []Action `json:"actions"`
Signatures []string `json:"signatures"`
}
// Define Context Keys
type contextKey string
var (
transactionsKey = contextKey("transactions")
)
var client = http.Client{}
// getHost returns the host based on the existence of the X-Forwarded-For header.
func getHost(r *http.Request) string {
var remoteHost string
if header := r.Header.Get("X-Forwarded-For"); header != "" {
remoteHost = header
} else {
remoteHost = r.RemoteAddr
}
return remoteHost
}
// injectHeaders adds configured headers into response
func injectHeaders(headers http.Header) {
for header, value := range appConfig.Headers {
if value != "" {
headers.Set(header, value)
} else {
headers.Del(header)
}
}
}
// logFailure logs a failure to the Fail2Ban server
func logFailure(message string, w http.ResponseWriter, r *http.Request, statusCode int) {
// Default status code
if statusCode < 100 {
statusCode = 400
}
remoteHost := getHost(r)
for _, logAgent := range appConfig.LogEndpoints {
if !strings.Contains(logAgent, "/patroneos/fail2ban-relay") {
logAgent += "/patroneos/fail2ban-relay"
}
logEvent := Log{
Host: remoteHost,
Success: false,
Message: message,
}
body, err := json.Marshal(logEvent)
if err != nil {
log.Printf("Error marshalling failure message %s", err)
}
_, err = client.Post(logAgent, "application/json", bytes.NewBuffer(body))
if err != nil {
log.Print(err)
}
}
log.Printf("Failure: %s %s", remoteHost, message)
if w != nil {
errorBody, _ := json.Marshal(ErrorMessage{Message: message, Code: statusCode})
w.Header().Add("X-REJECTED-BY", "patroneos")
w.Header().Add("CONTENT-TYPE", "application/json")
injectHeaders(w.Header())
w.WriteHeader(statusCode)
_, err := w.Write(errorBody)
if err != nil {
log.Printf("Error writing response body %s", err)
}
}
}
// logSuccess logs a success to the Fail2Ban server
func logSuccess(message string, r *http.Request) {
remoteHost := getHost(r)
for _, logAgent := range appConfig.LogEndpoints {
if !strings.Contains(logAgent, "/patroneos/fail2ban-relay") {
logAgent += "/patroneos/fail2ban-relay"
}
logEvent := Log{
Host: remoteHost,
Success: true,
Message: message,
}
body, err := json.Marshal(logEvent)
if err != nil {
log.Printf("Error marshalling success message %s", err)
}
_, err = client.Post(logAgent, "application/json", bytes.NewBuffer(body))
if err != nil {
log.Print(err)
}
}
log.Printf("Success: %s %s", remoteHost, message)
}
// validateJSON checks that the POST body contains a valid JSON object.
func validateJSON(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jsonBytes, err := ioutil.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(jsonBytes))
if len(jsonBytes) > 0 {
if !json.Valid(jsonBytes) || err != nil {
logFailure("INVALID_JSON", w, r, 0)
return
}
}
next.ServeHTTP(w, r)
}
}
// validateMaxSignatures checks that the transaction does not have more signatures than the max allowed.
func validateMaxSignatures(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
transactions, ctx, err := getTransactions(r)
if err != nil {
logFailure(err.Error(), w, r, 0)
return
}
for _, transaction := range transactions {
if len(transaction.Signatures) > appConfig.MaxSignatures {
logFailure("INVALID_NUMBER_SIGNATURES", w, r, 0)
return
}
}
next.ServeHTTP(w, r.WithContext(ctx))
}
}
// validateContract checks that the transaction does not act on a blacklisted contract.
func validateContract(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
transactions, ctx, err := getTransactions(r)
if err != nil {
logFailure(err.Error(), w, r, 0)
return
}
for _, transaction := range transactions {
for _, action := range transaction.Actions {
_, exists := appConfig.ContractBlackList[action.Code]
if exists {
logFailure("BLACKLISTED_CONTRACT", w, r, 0)
return
}
}
}
next.ServeHTTP(w, r.WithContext(ctx))
}
}
// validateMaxTransactions checks that the number of transactions in the request does not exceed the defined maximum.
func validateMaxTransactions(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
transactions, ctx, err := getTransactions(r)
if err != nil {
logFailure(err.Error(), w, r, 0)
return
}
// Skip this middleware if MaxTransactions is not configured, or set to 0
if appConfig.MaxTransactions > 0 {
if len(transactions) > appConfig.MaxTransactions {
logFailure("TOO_MANY_TRANSACTIONS", w, r, 0)
return
}
}
next.ServeHTTP(w, r.WithContext(ctx))
}
}
// validateTransactionSize checks that the transaction data does not exceed the max allowed size.
func validateTransactionSize(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
transactions, ctx, err := getTransactions(r)
if err != nil {
logFailure(err.Error(), w, r, 0)
return
}
for _, transaction := range transactions {
for _, action := range transaction.Actions {
if len(action.Data) > appConfig.MaxTransactionSize {
logFailure("INVALID_TRANSACTION_SIZE", w, r, 0)
return
}
}
}
next.ServeHTTP(w, r.WithContext(ctx))
}
}
// getTransactions parses json and returns a slice containing the transactions
func getTransactions(r *http.Request) ([]Transaction, context.Context, error) {
var transactions []Transaction
var transaction Transaction
// Context has not been set
if r.Context().Value(transactionsKey) == nil {
// Read request body
jsonBytes, _ := ioutil.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(jsonBytes))
// Determine if JSON is a single object or an array of objects
body := strings.TrimSpace(string(jsonBytes))
if strings.HasPrefix(body, "{") {
// Single Object
err := json.Unmarshal(jsonBytes, &transaction)
if err != nil {
return nil, nil, errors.New("PARSE_ERROR")
}
transactions = append(transactions, transaction)
} else if strings.HasPrefix(body, "[") {
// Array of Objects
err := json.Unmarshal(jsonBytes, &transactions)
if err != nil {
return nil, nil, errors.New("PARSE_ERROR")
}
}
// Add transactions to request context so subsequent middleware does not have to parse the transactions again
ctx := context.WithValue(r.Context(), transactionsKey, transactions)
return transactions, ctx, nil
}
// Context already exists
transactions = r.Context().Value(transactionsKey).([]Transaction)
return transactions, r.Context(), nil
}
// Walks through the middleware list in reverse order and
// pass the return value into the function before it so they are called
// in the correct order.
// Middleware pattern inspired by https://hackernoon.com/simple-http-middleware-with-go-79a4ad62889b
func chainMiddleware(mw ...middleware) middleware {
return func(final http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
last := final
for i := len(mw) - 1; i >= 0; i-- {
last = mw[i](last)
}
last(w, r)
}
}
}
func copyHeaders(response http.Header, request http.Header) {
for key, value := range request {
for _, header := range value {
response.Add(key, header)
}
}
}
// If the request passes all middleware validations
// we forward it to the node to be processed.
func forwardCallToNodeos(w http.ResponseWriter, r *http.Request) {
nodeosHost := fmt.Sprintf("%s://%s:%s", appConfig.NodeosProtocol, appConfig.NodeosURL, appConfig.NodeosPort)
url := nodeosHost + r.URL.String()
method := r.Method
body, _ := ioutil.ReadAll(r.Body)
request, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
log.Printf("Error in creating request %s", err)
logFailure("NODEOS_REQUEST_NOT_CREATED", w, r, 500)
return
}
// Forward headers to nodeos
request.Header = make(http.Header)
copyHeaders(request.Header, r.Header)
res, err := client.Do(request)
if err != nil {
log.Printf("Error in executing request %s", err)
logFailure("NODEOS_UNREACHABLE", w, r, 503)
return
}
defer res.Body.Close()
body, _ = ioutil.ReadAll(res.Body)
if res.StatusCode == 200 {
logSuccess("SUCCESS", r)
} else {
logFailure("TRANSACTION_FAILED", nil, r, 0)
}
copyHeaders(w.Header(), res.Header)
// Inject configured headers
injectHeaders(w.Header())
w.WriteHeader(res.StatusCode)
_, err = w.Write(body)
if err != nil {
log.Printf("Error writing response body %s", err)
return
}
}
func relay(w http.ResponseWriter, r *http.Request) {
message := "Patroneos cannot receive fail2ban relay requests when running in filter mode. Please check your config."
log.Printf("%s", message)
errorBody, _ := json.Marshal(ErrorMessage{Message: message, Code: 403})
w.WriteHeader(http.StatusForbidden)
_, err := w.Write(errorBody)
if err != nil {
log.Printf("Error writing response body %s", err)
return
}
}
func addFilterHandlers(mux *http.ServeMux) {
// Middleware are executed in the order that they are passed to chainMiddleware.
middlewareChain := chainMiddleware(
validateJSON,
validateMaxTransactions,
validateTransactionSize,
validateMaxSignatures,
validateContract,
)
mux.HandleFunc("/", middlewareChain(forwardCallToNodeos))
mux.HandleFunc("/patroneos/fail2ban-relay", relay)
}