From 08811a6da78c3f1f973b8f50a337ff4dc4ed9e2c Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Tue, 24 May 2022 17:42:00 -0600 Subject: Replace CSRF token checking with Referer checking --- srv/src/http/csrf.go | 64 ++++++---------------------------------------------- 1 file changed, 7 insertions(+), 57 deletions(-) (limited to 'srv/src/http/csrf.go') diff --git a/srv/src/http/csrf.go b/srv/src/http/csrf.go index 7a45269..d0f7b6a 100644 --- a/srv/src/http/csrf.go +++ b/srv/src/http/csrf.go @@ -3,76 +3,26 @@ package http import ( "errors" "net/http" + "net/url" "github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil" ) -const ( - csrfTokenCookieName = "csrf_token" - csrfTokenHeaderName = "X-CSRF-Token" - csrfTokenFormName = "csrfToken" -) - -func setCSRFMiddleware(h http.Handler) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - - csrfTok, err := apiutil.GetCookie(r, csrfTokenCookieName, "") - - if err != nil { - apiutil.InternalServerError(rw, r, err) - return - - } else if csrfTok == "" { - http.SetCookie(rw, &http.Cookie{ - Name: csrfTokenCookieName, - Value: apiutil.RandStr(32), - Secure: true, - }) - } - - h.ServeHTTP(rw, r) - }) -} - -func checkCSRFMiddleware(h http.Handler) http.Handler { +func (a *api) checkCSRFMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - csrfTok, err := apiutil.GetCookie(r, csrfTokenCookieName, "") - + refererURL, err := url.Parse(r.Referer()) if err != nil { - apiutil.InternalServerError(rw, r, err) + apiutil.BadRequest(rw, r, errors.New("invalid Referer")) return } - givenCSRFTok := r.Header.Get(csrfTokenHeaderName) - if givenCSRFTok == "" { - givenCSRFTok = r.FormValue(csrfTokenFormName) - } - - if csrfTok == "" || givenCSRFTok != csrfTok { - apiutil.BadRequest(rw, r, errors.New("invalid CSRF token")) + if refererURL.Scheme != a.params.PublicURL.Scheme || + refererURL.Host != a.params.PublicURL.Host { + apiutil.BadRequest(rw, r, errors.New("invalid Referer")) return } h.ServeHTTP(rw, r) }) } - -func (a *api) getCSRFTokenHandler() http.Handler { - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - - csrfTok, err := apiutil.GetCookie(r, csrfTokenCookieName, "") - - if err != nil { - apiutil.InternalServerError(rw, r, err) - return - } - - apiutil.JSONResult(rw, r, struct { - CSRFToken string - }{ - CSRFToken: csrfTok, - }) - }) -} -- cgit v1.2.3