commands/http: Made command HTTP API only accept requests from referers on the same server
Matt Bell committed
Feb 2, 2015 at 20:16 UTC
e8bbf1dcdf57f1bb3f6a279345aaded3744fa142
1 file changed
+15
commands/http/handler.go
+15
@@ -6,6 +6,7 @@ import (
6
"io"
7
"net/http"
8
"strconv"
9
+ "strings"
10
11
context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
12
@@ -55,6 +56,20 @@ func (i Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
56
57
log.Debug("Incoming API request: ", r.URL)
58
59
+ // error on external referers (to prevent CSRF attacks)
60
+ referer := r.Referer()
61
+ scheme := r.URL.Scheme
62
+ if len(scheme) == 0 {
63
+ scheme = "http"
64
+ }
65
+ host := fmt.Sprintf("%s://%s/", scheme, r.Host)
66
+ // empty string means the user isn't following a link (they are directly typing in the url)
67
+ if referer != "" && !strings.HasPrefix(referer, host) {
68
+ w.WriteHeader(http.StatusForbidden)
69
+ w.Write([]byte("403 - Forbidden"))
70
+ return
71
+ }
72
+
73
if len(i.origin) > 0 {
74
w.Header().Set("Access-Control-Allow-Origin", i.origin)
75
}