summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2022-08-18 20:59:53 -0600
committerBrian Picciano <mediocregopher@gmail.com>2022-08-18 20:59:53 -0600
commit98e0c3e89c1a72aa93895dcab446e8b15a5b3511 (patch)
tree888b15b53c5c6caf189d73d78d6b9ce4c45ae0a3
parentf7b4fd644b33111802c0c75a0b5790a4cef96c86 (diff)
fix CSRF checking so that localhost always works
-rw-r--r--srv/src/http/csrf.go31
1 files changed, 23 insertions, 8 deletions
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
}