forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcsrf.go
167 lines (139 loc) · 4.09 KB
/
csrf.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
package csrf
import (
"errors"
"fmt"
"net/http"
"net/url"
"reflect"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
type Service interface {
Middleware() func(http.Handler) http.Handler
TrustOrigin(origin string)
AddAdditionalHeaders(headerName string)
AddSafeEndpoint(endpoint string)
}
type CSRF struct {
cfg *setting.Cfg
trustedOrigins map[string]struct{}
headers map[string]struct{}
safeEndpoints map[string]struct{}
alwaysCheck bool
}
func ProvideCSRFFilter(cfg *setting.Cfg) *CSRF {
c := &CSRF{
cfg: cfg,
trustedOrigins: map[string]struct{}{},
headers: map[string]struct{}{},
safeEndpoints: map[string]struct{}{},
}
additionalHeaders := cfg.SectionWithEnvOverrides("security").Key("csrf_additional_headers").Strings(" ")
trustedOrigins := cfg.SectionWithEnvOverrides("security").Key("csrf_trusted_origins").Strings(" ")
c.alwaysCheck = cfg.SectionWithEnvOverrides("security").Key("csrf_always_check").MustBool(false)
for _, header := range additionalHeaders {
c.headers[header] = struct{}{}
}
for _, origin := range trustedOrigins {
c.trustedOrigins[origin] = struct{}{}
}
return c
}
func (c *CSRF) Middleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
e := &errorWithStatus{}
err := c.check(r)
if err != nil {
if !errors.As(err, &e) {
http.Error(w, fmt.Sprintf("internal server error: expected error type errorWithStatus, got %s. Error: %v", reflect.TypeOf(err), err), http.StatusInternalServerError)
}
http.Error(w, err.Error(), e.HTTPStatus)
return
}
next.ServeHTTP(w, r)
})
}
}
func (c *CSRF) check(r *http.Request) error {
// As per RFC 7231/4.2.2 these methods are idempotent:
// (GET is excluded because it may have side effects in some APIs)
safeMethods := []string{"HEAD", "OPTIONS", "TRACE"}
// If the CSRF checks can be skipped.
if !c.alwaysCheck {
// If request has no login cookie - skip CSRF checks
if _, err := r.Cookie(c.cfg.LoginCookieName); errors.Is(err, http.ErrNoCookie) {
return nil
}
}
// Skip CSRF checks for "safe" methods
for _, method := range safeMethods {
if r.Method == method {
return nil
}
}
// Skip CSRF checks for "safe" endpoints
for safeEndpoint := range c.safeEndpoints {
if r.URL.Path == safeEndpoint {
return nil
}
}
// Otherwise - verify that Origin matches the server origin
netAddr, err := util.SplitHostPortDefault(r.Host, "", "0") // we ignore the port
if err != nil {
return &errorWithStatus{Underlying: err, HTTPStatus: http.StatusBadRequest}
}
o := r.Header.Get("Origin")
// No Origin header sent, skip CSRF check.
if o == "" {
return nil
}
originURL, err := url.Parse(o)
if err != nil {
return &errorWithStatus{Underlying: err, HTTPStatus: http.StatusBadRequest}
}
origin := originURL.Hostname()
trustedOrigin := false
for h := range c.headers {
customHost := r.Header.Get(h)
addr, err := util.SplitHostPortDefault(customHost, "", "0") // we ignore the port
if err != nil {
return &errorWithStatus{Underlying: err, HTTPStatus: http.StatusBadRequest}
}
if addr.Host == origin {
trustedOrigin = true
break
}
}
for o := range c.trustedOrigins {
if o == origin {
trustedOrigin = true
break
}
}
hostnameMatches := origin == netAddr.Host
if netAddr.Host == "" || !trustedOrigin && !hostnameMatches {
return &errorWithStatus{Underlying: errors.New("origin not allowed"), HTTPStatus: http.StatusForbidden}
}
return nil
}
func (c *CSRF) TrustOrigin(origin string) {
c.trustedOrigins[origin] = struct{}{}
}
func (c *CSRF) AddAdditionalHeaders(headerName string) {
c.headers[headerName] = struct{}{}
}
// AddSafeEndpoint is used for endpoints requests to skip CSRF check
func (c *CSRF) AddSafeEndpoint(endpoint string) {
c.safeEndpoints[endpoint] = struct{}{}
}
type errorWithStatus struct {
Underlying error
HTTPStatus int
}
func (e errorWithStatus) Error() string {
return e.Underlying.Error()
}
func (e errorWithStatus) Unwrap() error {
return e.Underlying
}