forked from traefik/traefik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip_whitelister.go
64 lines (51 loc) · 1.73 KB
/
ip_whitelister.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
package middlewares
import (
"fmt"
"net/http"
"github.com/containous/traefik/log"
"github.com/containous/traefik/middlewares/tracing"
"github.com/containous/traefik/whitelist"
"github.com/pkg/errors"
"github.com/urfave/negroni"
)
// IPWhiteLister is a middleware that provides Checks of the Requesting IP against a set of Whitelists
type IPWhiteLister struct {
handler negroni.Handler
whiteLister *whitelist.IP
}
// NewIPWhiteLister builds a new IPWhiteLister given a list of CIDR-Strings to whitelist
func NewIPWhiteLister(whiteList []string, useXForwardedFor bool) (*IPWhiteLister, error) {
if len(whiteList) == 0 {
return nil, errors.New("no white list provided")
}
whiteLister := IPWhiteLister{}
ip, err := whitelist.NewIP(whiteList, false, useXForwardedFor)
if err != nil {
return nil, fmt.Errorf("parsing CIDR whitelist %s: %v", whiteList, err)
}
whiteLister.whiteLister = ip
whiteLister.handler = negroni.HandlerFunc(whiteLister.handle)
log.Debugf("configured IP white list: %s", whiteList)
return &whiteLister, nil
}
func (wl *IPWhiteLister) handle(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
err := wl.whiteLister.IsAuthorized(r)
if err != nil {
tracing.SetErrorAndDebugLog(r, "request %+v - rejecting: %v", r, err)
reject(w)
return
}
tracing.SetErrorAndDebugLog(r, "request %+v matched white list %s - passing", r, wl.whiteLister)
next.ServeHTTP(w, r)
}
func (wl *IPWhiteLister) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
wl.handler.ServeHTTP(rw, r, next)
}
func reject(w http.ResponseWriter) {
statusCode := http.StatusForbidden
w.WriteHeader(statusCode)
_, err := w.Write([]byte(http.StatusText(statusCode)))
if err != nil {
log.Error(err)
}
}