-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
middleware.go
330 lines (271 loc) · 8.89 KB
/
middleware.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
package utils
import (
"context"
"net/http"
"time"
"net"
"strings"
"fmt"
"github.com/mxk/go-flowrate/flowrate"
"github.com/oschwald/geoip2-golang"
)
// https://github.com/go-chi/chi/blob/master/middleware/timeout.go
func MiddlewareTimeout(timeout time.Duration) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer func() {
cancel()
if ctx.Err() == context.DeadlineExceeded {
Error("Request Timeout. Cancelling.", ctx.Err())
HTTPError(w, "Gateway Timeout",
http.StatusGatewayTimeout, "HTTP002")
return
}
}()
w.Header().Set("X-Timeout-Duration", timeout.String())
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
type responseWriter struct {
http.ResponseWriter
*flowrate.Writer
}
func (w *responseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func BandwithLimiterMiddleware(max int64) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if(max > 0) {
fw := flowrate.NewWriter(w, max)
w = &responseWriter{w, fw}
}
next.ServeHTTP(w, r)
})
}
}
func SetSecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if(IsHTTPS) {
// TODO: Add preload if we have a valid certificate
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-XSS-Protection", "1; mode=block")
w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'")
w.Header().Set("X-Served-By-Cosmos", "1")
next.ServeHTTP(w, r)
})
}
func CORSHeader(origin string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
next.ServeHTTP(w, r)
})
}
}
func AcceptHeader(accept string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", accept)
next.ServeHTTP(w, r)
})
}
}
// GetIPLocation returns the ISO country code for a given IP address.
func GetIPLocation(ip string) (string, error) {
geoDB, err := geoip2.Open("GeoLite2-Country.mmdb")
if err != nil {
return "", err
}
defer geoDB.Close()
parsedIP := net.ParseIP(ip)
record, err := geoDB.Country(parsedIP)
if err != nil {
return "", err
}
return record.Country.IsoCode, nil
}
// BlockByCountryMiddleware returns a middleware function that blocks requests from specified countries.
func BlockByCountryMiddleware(blockedCountries []string, CountryBlacklistIsWhitelist bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
countryCode, err := GetIPLocation(ip)
if err == nil {
if countryCode == "" {
Debug("Country code is empty")
} else {
Debug("Country code: " + countryCode)
}
config := GetMainConfig()
if CountryBlacklistIsWhitelist {
if countryCode != "" {
blocked := true
for _, blockedCountry := range blockedCountries {
if config.ServerCountry != countryCode && countryCode == blockedCountry {
blocked = false
}
}
if blocked {
http.Error(w, "Access denied", http.StatusForbidden)
return
}
} else {
Warn("Missing geolocation information to block IPs")
}
} else {
for _, blockedCountry := range blockedCountries {
if config.ServerCountry != countryCode && countryCode == blockedCountry {
http.Error(w, "Access denied", http.StatusForbidden)
return
}
}
}
} else {
Warn("Missing geolocation information to block IPs")
}
next.ServeHTTP(w, r)
})
}
}
// blockPostWithoutReferer blocks POST requests without a Referer header
func BlockPostWithoutReferer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" || r.Method == "DELETE" {
referer := r.Header.Get("Referer")
if referer == "" {
Error("Blocked POST request without Referer header", nil)
http.Error(w, "Bad Request: Invalid request.", http.StatusBadRequest)
return
}
}
// If it's not a POST request or the POST request has a Referer header, pass the request to the next handler
next.ServeHTTP(w, r)
})
}
func EnsureHostname(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Debug("Ensuring origin for requested resource from : " + r.Host)
og := GetMainConfig().HTTPConfig.Hostname
ni := GetMainConfig().NewInstall
if ni || og == "0.0.0.0" {
next.ServeHTTP(w, r)
return
}
hostnames := GetAllHostnames(false, false)
reqHostNoPort := strings.Split(r.Host, ":")[0]
isOk := false
for _, hostname := range hostnames {
hostnameNoPort := strings.Split(hostname, ":")[0]
if reqHostNoPort == hostnameNoPort {
isOk = true
}
}
if !isOk {
Error("Invalid Hostname " + r.Host + " for request. Expecting one of " + fmt.Sprintf("%v", hostnames), nil)
w.WriteHeader(http.StatusBadRequest)
http.Error(w, "Bad Request: Invalid hostname. Use your domain instead of your IP to access your server. Check logs if more details are needed.", http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
}
func IsValidHostname(hostname string) bool {
og := GetMainConfig().HTTPConfig.Hostname
ni := GetMainConfig().NewInstall
if ni || og == "0.0.0.0" {
return true
}
hostnames := GetAllHostnames(false, false)
reqHostNoPort := strings.Split(hostname, ":")[0]
reqHostNoPortNoSubdomain := ""
if parts := strings.Split(reqHostNoPort, "."); len(parts) < 2 {
reqHostNoPortNoSubdomain = reqHostNoPort
} else {
reqHostNoPortNoSubdomain = parts[len(parts)-2] + "." + parts[len(parts)-1]
}
for _, hostname := range hostnames {
hostnameNoPort := strings.Split(hostname, ":")[0]
hostnameNoPortNoSubdomain := ""
if parts := strings.Split(hostnameNoPort, "."); len(parts) < 2 {
hostnameNoPortNoSubdomain = hostnameNoPort
} else {
hostnameNoPortNoSubdomain = parts[len(parts)-2] + "." + parts[len(parts)-1]
}
if reqHostNoPortNoSubdomain == hostnameNoPortNoSubdomain {
return true
}
}
return false
}
func IPInRange(ipStr, cidrStr string) (bool, error) {
_, cidrNet, err := net.ParseCIDR(cidrStr)
if err != nil {
return false, fmt.Errorf("parse CIDR range: %w", err)
}
ip := net.ParseIP(ipStr)
if ip == nil {
return false, fmt.Errorf("parse IP: invalid IP address")
}
return cidrNet.Contains(ip), nil
}
func Restrictions(RestrictToConstellation bool, WhitelistInboundIPs []string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
isUsingWhiteList := len(WhitelistInboundIPs) > 0
isInWhitelist := false
isInConstellation := strings.HasPrefix(ip, "192.168.201.") || strings.HasPrefix(ip, "192.168.202.")
for _, ipRange := range WhitelistInboundIPs {
Debug("Checking if " + ip + " is in " + ipRange)
if strings.Contains(ipRange, "/") {
if ok, _ := IPInRange(ip, ipRange); ok {
isInWhitelist = true
}
} else {
if ip == ipRange {
isInWhitelist = true
}
}
}
if(RestrictToConstellation) {
if(!isInConstellation) {
if(!isUsingWhiteList) {
Error("Request from " + ip + " is blocked because of restrictions", nil)
Debug("Blocked by RestrictToConstellation isInConstellation isUsingWhiteList")
http.Error(w, "Access denied", http.StatusForbidden)
return
} else if (!isInWhitelist) {
Error("Request from " + ip + " is blocked because of restrictions", nil)
Debug("Blocked by RestrictToConstellation isInConstellation isInWhitelist")
http.Error(w, "Access denied", http.StatusForbidden)
return
}
}
} else if(isUsingWhiteList && !isInWhitelist) {
Error("Request from " + ip + " is blocked because of restrictions", nil)
Debug("Blocked by RestrictToConstellation isInConstellation isUsingWhiteList isInWhitelist")
http.Error(w, "Access denied", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}