From 98e0c3e89c1a72aa93895dcab446e8b15a5b3511 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Thu, 18 Aug 2022 20:59:53 -0600 Subject: fix CSRF checking so that localhost always works --- srv/src/http/csrf.go | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) (limited to 'srv/src/http') diff --git a/srv/src/http/csrf.go b/srv/src/http/csrf.go index d0f7b6a..a64e37e 100644 --- a/srv/src/http/csrf.go +++ b/srv/src/http/csrf.go @@ -2,23 +2,38 @@ package http import ( "errors" + "net" "net/http" "net/url" "github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil" ) -func (a *api) checkCSRFMiddleware(h http.Handler) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { +func checkCSRF(r *http.Request, publicURL *url.URL) error { - refererURL, err := url.Parse(r.Referer()) - if err != nil { - apiutil.BadRequest(rw, r, errors.New("invalid Referer")) - return + if ipStr, _, err := net.SplitHostPort(r.Host); err == nil { + if ip := net.ParseIP(ipStr); ip != nil && ip.IsLoopback() { + return nil } + } + + refererURL, err := url.Parse(r.Referer()) + if err != nil { + return errors.New("invalid Referer") + } + + if refererURL.Scheme != publicURL.Scheme || + refererURL.Host != publicURL.Host { + return errors.New("invalid Referer") + } + + return nil +} + +func (a *api) checkCSRFMiddleware(h http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if refererURL.Scheme != a.params.PublicURL.Scheme || - refererURL.Host != a.params.PublicURL.Host { + if err := checkCSRF(r, a.params.PublicURL); err != nil { apiutil.BadRequest(rw, r, errors.New("invalid Referer")) return } -- cgit v1.2.3