API: Migrate CSRF to service and support additional options (#48120)

* API: Migrate CSRF to service and support additional options

* minor

* public Csrf service to use in tests

* WIP

* remove fmt

* comment

* WIP

* remove fmt prints

* todo add prefix slash

* remove fmt prints

* linting fix

* remove trimPrefix

Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>
Co-authored-by: IevaVasiljeva <ieva.vasiljeva@grafana.com>
This commit is contained in:
Emil Tullstedt
2022-06-02 15:52:30 +02:00
committed by GitHub
co-authored by Eric Leijonmarck IevaVasiljeva
parent 84860ffc96
commit 3e81fa0716
5 changed files with 149 additions and 58 deletions
+130
View File
@@ -0,0 +1,130 @@
package csrf
import (
"errors"
"net/http"
"net/url"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
type Service interface {
Middleware(logger log.Logger) func(http.Handler) http.Handler
TrustOrigin(origin string)
AddOriginHeader(headerName string)
AddSafeEndpoint(endpoint string)
}
type Implementation struct {
cfg *setting.Cfg
trustedOrigins map[string]struct{}
originHeaders map[string]struct{}
safeEndpoints map[string]struct{}
}
func ProvideCSRFFilter(cfg *setting.Cfg) Service {
i := &Implementation{
cfg: cfg,
trustedOrigins: map[string]struct{}{},
originHeaders: map[string]struct{}{
"Origin": {},
},
safeEndpoints: map[string]struct{}{},
}
additionalHeaders := cfg.SectionWithEnvOverrides("security").Key("csrf_additional_headers").Strings(" ")
trustedOrigins := cfg.SectionWithEnvOverrides("security").Key("csrf_trusted_origins").Strings(" ")
for _, header := range additionalHeaders {
i.originHeaders[header] = struct{}{}
}
for _, origin := range trustedOrigins {
i.trustedOrigins[origin] = struct{}{}
}
return i
}
func (i *Implementation) Middleware(logger log.Logger) func(http.Handler) http.Handler {
// 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"}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// If request has no login cookie - skip CSRF checks
if _, err := r.Cookie(i.cfg.LoginCookieName); errors.Is(err, http.ErrNoCookie) {
next.ServeHTTP(w, r)
return
}
// Skip CSRF checks for "safe" methods
for _, method := range safeMethods {
if r.Method == method {
next.ServeHTTP(w, r)
return
}
}
// Skip CSRF checks for "safe" endpoints
for safeEndpoint := range i.safeEndpoints {
if r.URL.Path == safeEndpoint {
next.ServeHTTP(w, r)
return
}
}
// Otherwise - verify that Origin matches the server origin
netAddr, err := util.SplitHostPortDefault(r.Host, "", "0") // we ignore the port
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
origins := map[string]struct{}{}
for header := range i.originHeaders {
origin, err := url.Parse(r.Header.Get(header))
if err != nil {
logger.Error("error parsing Origin header", "header", header, "err", err)
}
if origin.String() != "" {
origins[origin.Hostname()] = struct{}{}
}
}
// No Origin header sent, skip CSRF check.
if len(origins) == 0 {
next.ServeHTTP(w, r)
return
}
trustedOrigin := false
for o := range i.trustedOrigins {
if _, ok := origins[o]; ok {
trustedOrigin = true
break
}
}
_, hostnameMatches := origins[netAddr.Host]
if netAddr.Host == "" || !trustedOrigin && !hostnameMatches {
http.Error(w, "origin not allowed", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
func (i *Implementation) TrustOrigin(origin string) {
i.trustedOrigins[origin] = struct{}{}
}
func (i *Implementation) AddOriginHeader(headerName string) {
i.originHeaders[headerName] = struct{}{}
}
// AddSafeEndpoint is used for endpoints requests to skip CSRF check
func (i *Implementation) AddSafeEndpoint(endpoint string) {
i.safeEndpoints[endpoint] = struct{}{}
}
+129
View File
@@ -0,0 +1,129 @@
package csrf
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
)
func TestMiddlewareCSRF(t *testing.T) {
tests := []struct {
name string
cookieName string
method string
origin string
host string
code int
}{
{
name: "mismatched origin and host is forbidden",
cookieName: "foo",
method: "GET",
origin: "http://notLocalhost",
host: "localhost",
code: http.StatusForbidden,
},
{
name: "mismatched origin and host is NOT forbidden with a 'Safe Method'",
cookieName: "foo",
method: "TRACE",
origin: "http://notLocalhost",
host: "localhost",
code: http.StatusOK,
},
{
name: "mismatched origin and host is NOT forbidden without a cookie",
cookieName: "",
method: "GET",
origin: "http://notLocalhost",
host: "localhost",
code: http.StatusOK,
},
{
name: "malformed host is a bad request",
cookieName: "foo",
method: "GET",
host: "localhost:80:80",
code: http.StatusBadRequest,
},
{
name: "host works without port",
cookieName: "foo",
method: "GET",
host: "localhost",
origin: "http://localhost",
code: http.StatusOK,
},
{
name: "port does not have to match",
cookieName: "foo",
method: "GET",
host: "localhost:80",
origin: "http://localhost:3000",
code: http.StatusOK,
},
{
name: "IPv6 host works with port",
cookieName: "foo",
method: "GET",
host: "[::1]:3000",
origin: "http://[::1]:3000",
code: http.StatusOK,
},
{
name: "IPv6 host (with longer address) works with port",
cookieName: "foo",
method: "GET",
host: "[2001:db8::1]:3000",
origin: "http://[2001:db8::1]:3000",
code: http.StatusOK,
},
{
name: "IPv6 host (with longer address) works without port",
cookieName: "foo",
method: "GET",
host: "[2001:db8::1]",
origin: "http://[2001:db8::1]",
code: http.StatusOK,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rr := csrfScenario(t, tt.cookieName, tt.method, tt.origin, tt.host)
require.Equal(t, tt.code, rr.Code)
})
}
}
func csrfScenario(t *testing.T, cookieName, method, origin, host string) *httptest.ResponseRecorder {
req, err := http.NewRequest(method, "/", nil)
if err != nil {
t.Fatal(err)
}
req.AddCookie(&http.Cookie{
Name: cookieName,
})
// Note: Not sure where host header populates req.Host, or how that works.
req.Host = host
req.Header.Set("HOST", host)
req.Header.Set("ORIGIN", origin)
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
})
rr := httptest.NewRecorder()
cfg := setting.NewCfg()
cfg.LoginCookieName = cookieName
service := ProvideCSRFFilter(cfg)
handler := service.Middleware(log.New())(testHandler)
handler.ServeHTTP(rr, req)
return rr
}