Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Fix CSRF bypass via Accept header (GHSA-xjr8-w967-4xjq)

Matt Robertsd7dcddd16bea
diff --git a/app/middlewares/security.go b/app/middlewares/security.go
index 0f407ec74..e232e60a4 100644
--- a/app/middlewares/security.go
+++ b/app/middlewares/security.go
@@ -2,6 +2,8 @@ package middlewares
import (
"fmt"
+ "mime"
+ "net/http"
"strings"
"github.com/getfider/fider/app/pkg/env"
@@ -32,15 +34,67 @@ func Secure() web.MiddlewareFunc {
}
}
-// Secure middleware is responsible for blocking CSRF attacks
+// CSRF middleware is responsible for blocking Cross-Site Request Forgery attacks.
+//
+// A state-changing request (anything other than GET/HEAD/OPTIONS) is only
+// allowed when it carries a signal that a cross-origin web page cannot produce
+// without first passing a CORS preflight (which Fider never grants):
+//
+// - a Content-Type whose media type is exactly "application/json"; or
+// - an "Authorization: Bearer ..." header (API key clients).
+//
+// The Accept header is deliberately NOT considered: it is CORS-safelisted, so a
+// cross-origin page can send "Accept: application/json" in a no-cors request.
+//
+// As defence in depth, requests that the browser labels as
+// "Sec-Fetch-Site: cross-site" are rejected. "same-site" is allowed so that
+// multi-tenant subdomains keep working, and requests without the header
+// (non-browser clients, older browsers) are unaffected.
func CSRF() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
return func(c *web.Context) error {
- var isWriteRequest = c.Request.Method == "POST" || c.Request.Method == "PUT" || c.Request.Method == "DELETE"
- if isWriteRequest && !c.IsAjax() {
- return c.Forbidden()
+ if isWriteMethod(c.Request.Method) {
+ if strings.EqualFold(c.Request.GetHeader("Sec-Fetch-Site"), "cross-site") {
+ return c.Forbidden()
+ }
+ if !hasJSONContentType(c) && !hasBearerAuthorization(c) {
+ return c.Forbidden()
+ }
}
return next(c)
}
}
}
+
+func isWriteMethod(method string) bool {
+ switch method {
+ case http.MethodGet, http.MethodHead, http.MethodOptions:
+ return false
+ default:
+ return true
+ }
+}
+
+// hasJSONContentType returns true only if the Content-Type media type is exactly
+// application/json. Substring matching is unsafe, as "text/plain; x=application/json"
+// is a CORS-safelisted Content-Type.
+func hasJSONContentType(c *web.Context) bool {
+ contentType := c.Request.GetHeader("Content-Type")
+ if contentType == "" {
+ return false
+ }
+ mediaType, _, err := mime.ParseMediaType(contentType)
+ if err != nil {
+ return false
+ }
+ return mediaType == web.JSONContentType
+}
+
+// hasBearerAuthorization returns true if the request has an Authorization header
+// using the Bearer scheme. Browsers never attach Bearer credentials automatically
+// (unlike cached Basic credentials), and cross-origin pages cannot set this header
+// without a CORS preflight.
+func hasBearerAuthorization(c *web.Context) bool {
+ auth := strings.TrimSpace(c.Request.GetHeader("Authorization"))
+ return len(auth) > len("Bearer ") && strings.EqualFold(auth[:len("Bearer ")], "Bearer ")
+}
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index d0e73dafe..5d8af536c 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -3,6 +3,7 @@ package middlewares_test
import (
"net/http"
"testing"
+ "time"
"github.com/getfider/fider/app/middlewares"
. "github.com/getfider/fider/app/pkg/assert"
@@ -77,3 +78,84 @@ func TestSecureWithCDN_SingleHost(t *testing.T) {
Expect(response.Header().Get("X-Content-Type-Options")).Equals("nosniff")
Expect(response.Header().Get("Referrer-Policy")).Equals("no-referrer-when-downgrade")
}
+
+func executeCSRF(method string, headers map[string]string) int {
+ server := mock.NewServer()
+ server.Use(func(next web.HandlerFunc) web.HandlerFunc {
+ return func(c *web.Context) error {
+ c.Request.Method = method
+ return next(c)
+ }
+ })
+ server.Use(middlewares.CSRF())
+ for k, v := range headers {
+ server.AddHeader(k, v)
+ }
+ status, _ := server.Execute(func(c *web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+ return status
+}
+
+// See GHSA-xjr8-w967-4xjq
+func TestCSRF(t *testing.T) {
+ RegisterT(t)
+
+ testCases := []struct {
+ name string
+ method string
+ headers map[string]string
+ expected int
+ }{
+ {"GET without headers", "GET", map[string]string{}, http.StatusOK},
+ {"GET cross-site", "GET", map[string]string{"Sec-Fetch-Site": "cross-site"}, http.StatusOK},
+ {"HEAD without headers", "HEAD", map[string]string{}, http.StatusOK},
+ {"POST without headers", "POST", map[string]string{}, http.StatusForbidden},
+ {"POST with only Accept json", "POST", map[string]string{"Accept": "application/json"}, http.StatusForbidden},
+ {"PUT with only Accept json", "PUT", map[string]string{"Accept": "application/json"}, http.StatusForbidden},
+ {"DELETE with only Accept json", "DELETE", map[string]string{"Accept": "application/json"}, http.StatusForbidden},
+ {"PATCH with only Accept json", "PATCH", map[string]string{"Accept": "application/json"}, http.StatusForbidden},
+ {"POST with JSON content type", "POST", map[string]string{"Content-Type": "application/json"}, http.StatusOK},
+ {"POST with JSON content type and charset", "POST", map[string]string{"Content-Type": "application/json; charset=utf-8"}, http.StatusOK},
+ {"POST with upper-case JSON content type", "POST", map[string]string{"Content-Type": "Application/JSON"}, http.StatusOK},
+ {"PUT with JSON content type", "PUT", map[string]string{"Content-Type": "application/json"}, http.StatusOK},
+ {"DELETE with JSON content type", "DELETE", map[string]string{"Content-Type": "application/json"}, http.StatusOK},
+ {"POST with text/plain smuggling json", "POST", map[string]string{"Content-Type": "text/plain; x=application/json"}, http.StatusForbidden},
+ {"POST with text/plain and Accept json", "POST", map[string]string{"Content-Type": "text/plain", "Accept": "application/json"}, http.StatusForbidden},
+ {"POST with form content type", "POST", map[string]string{"Content-Type": "application/x-www-form-urlencoded"}, http.StatusForbidden},
+ {"POST with multipart content type", "POST", map[string]string{"Content-Type": "multipart/form-data; boundary=x"}, http.StatusForbidden},
+ {"POST with json-like content type", "POST", map[string]string{"Content-Type": "application/jsonx"}, http.StatusForbidden},
+ {"POST with invalid content type", "POST", map[string]string{"Content-Type": "application/json;;;="}, http.StatusForbidden},
+ {"POST with Bearer Authorization", "POST", map[string]string{"Authorization": "Bearer some-api-key"}, http.StatusOK},
+ {"DELETE with Bearer Authorization", "DELETE", map[string]string{"Authorization": "Bearer some-api-key"}, http.StatusOK},
+ {"POST with Basic Authorization", "POST", map[string]string{"Authorization": "Basic dXNlcjpwYXNz"}, http.StatusForbidden},
+ {"POST with empty Bearer Authorization", "POST", map[string]string{"Authorization": "Bearer "}, http.StatusForbidden},
+ {"POST cross-site with JSON content type", "POST", map[string]string{"Content-Type": "application/json", "Sec-Fetch-Site": "cross-site"}, http.StatusForbidden},
+ {"POST cross-site with Bearer Authorization", "POST", map[string]string{"Authorization": "Bearer some-api-key", "Sec-Fetch-Site": "cross-site"}, http.StatusForbidden},
+ {"POST same-site with JSON content type", "POST", map[string]string{"Content-Type": "application/json", "Sec-Fetch-Site": "same-site"}, http.StatusOK},
+ {"POST same-origin with JSON content type", "POST", map[string]string{"Content-Type": "application/json", "Sec-Fetch-Site": "same-origin"}, http.StatusOK},
+ {"POST user-initiated with JSON content type", "POST", map[string]string{"Content-Type": "application/json", "Sec-Fetch-Site": "none"}, http.StatusOK},
+ }
+
+ for _, tc := range testCases {
+ status := executeCSRF(tc.method, tc.headers)
+ if status != tc.expected {
+ t.Errorf("%s: expected status %d, got %d", tc.name, tc.expected, status)
+ }
+ }
+}
+
+func TestAuthCookieIsSameSiteLax(t *testing.T) {
+ RegisterT(t)
+
+ server := mock.NewServer()
+ _, response := server.Execute(func(c *web.Context) error {
+ c.AddCookie(web.CookieAuthName, "token", time.Now().Add(time.Hour))
+ return c.NoContent(http.StatusOK)
+ })
+
+ cookie := web.ParseCookie(response.Header().Get("Set-Cookie"))
+ Expect(cookie.Name).Equals(web.CookieAuthName)
+ Expect(cookie.SameSite).Equals(http.SameSiteLaxMode)
+ Expect(cookie.HttpOnly).IsTrue()
+}
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 4857bcded..172d2e9f5 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -358,6 +358,7 @@ func (c *Context) AddCookie(name, value string, expires time.Time) *http.Cookie
Path: "/",
Expires: expires,
Secure: c.Request.IsSecure,
+ SameSite: http.SameSiteLaxMode,
}
http.SetCookie(&c.Response, cookie)
return cookie
@@ -372,6 +373,7 @@ func (c *Context) RemoveCookie(name string) {
MaxAge: -1,
Expires: time.Now().Add(-100 * time.Hour),
Secure: c.Request.IsSecure,
+ SameSite: http.SameSiteLaxMode,
})
}
diff --git a/app/pkg/web/util/webutil.go b/app/pkg/web/util/webutil.go
index e1dff7611..5819d8fba 100644
--- a/app/pkg/web/util/webutil.go
+++ b/app/pkg/web/util/webutil.go
@@ -30,18 +30,18 @@ func encode(user *entity.User) string {
return token
}
-//AddAuthUserCookie generates Auth Token and adds a cookie
+// AddAuthUserCookie generates Auth Token and adds a cookie
func AddAuthUserCookie(ctx *web.Context, user *entity.User) {
AddAuthTokenCookie(ctx, encode(user))
}
-//AddAuthTokenCookie adds given token to a cookie
+// AddAuthTokenCookie adds given token to a cookie
func AddAuthTokenCookie(ctx *web.Context, token string) {
expiresAt := time.Now().Add(365 * 24 * time.Hour)
ctx.AddCookie(web.CookieAuthName, token, expiresAt)
}
-//SetSignUpAuthCookie sets a temporary domain-wide Auth Token
+// SetSignUpAuthCookie sets a temporary domain-wide Auth Token
func SetSignUpAuthCookie(ctx *web.Context, user *entity.User) {
http.SetCookie(&ctx.Response, &http.Cookie{
Name: web.CookieSignUpAuthName,
@@ -51,10 +51,11 @@ func SetSignUpAuthCookie(ctx *web.Context, user *entity.User) {
Path: "/",
Expires: time.Now().Add(5 * time.Minute),
Secure: ctx.Request.IsSecure,
+ SameSite: http.SameSiteLaxMode,
})
}
-//GetSignUpAuthCookie returns the temporary temporary domain-wide Auth Token and removes it
+// GetSignUpAuthCookie returns the temporary temporary domain-wide Auth Token and removes it
func GetSignUpAuthCookie(ctx *web.Context) string {
cookie, err := ctx.Request.Cookie(web.CookieSignUpAuthName)
if err == nil {
@@ -66,6 +67,7 @@ func GetSignUpAuthCookie(ctx *web.Context) string {
MaxAge: -1,
Expires: time.Now().Add(-100 * time.Hour),
Secure: ctx.Request.IsSecure,
+ SameSite: http.SameSiteLaxMode,
})
return cookie.Value
}