Improve dev mode API security

This commit is contained in:
Daniel 2021-11-23 12:58:01 +01:00
parent 140389d142
commit 93ff8eb19a

View file

@ -4,11 +4,14 @@ import (
"context" "context"
"errors" "errors"
"net/http" "net/http"
"net/url"
"path" "path"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/safing/portbase/utils"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/safing/portbase/log" "github.com/safing/portbase/log"
@ -21,6 +24,11 @@ var (
// main server and lock // main server and lock
server = &http.Server{} server = &http.Server{}
handlerLock sync.RWMutex handlerLock sync.RWMutex
allowedDevCORSOrigins = []string{
"127.0.0.1",
"localhost",
}
) )
// RegisterHandler registers a handler with the API endoint. // RegisterHandler registers a handler with the API endoint.
@ -139,6 +147,12 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error {
} }
// Add security headers. // Add security headers.
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "deny")
w.Header().Set("X-XSS-Protection", "1; mode=block")
w.Header().Set("X-DNS-Prefetch-Control", "off")
// Add CSP Header in production mode.
if !devMode() { if !devMode() {
w.Header().Set( w.Header().Set(
"Content-Security-Policy", "Content-Security-Policy",
@ -147,13 +161,12 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error {
"style-src 'self' 'unsafe-inline'; "+ "style-src 'self' 'unsafe-inline'; "+
"img-src 'self' data:", "img-src 'self' data:",
) )
w.Header().Set("Referrer-Policy", "no-referrer") } else if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("X-Content-Type-Options", "nosniff") // Allow cross origin requests from localhost in dev mode.
w.Header().Set("X-Frame-Options", "deny") if u, err := url.Parse(origin); err == nil &&
w.Header().Set("X-XSS-Protection", "1; mode=block") utils.StringInSlice(allowedDevCORSOrigins, u.Host) {
w.Header().Set("X-DNS-Prefetch-Control", "off") w.Header().Set("Access-Control-Allow-Origin", origin)
} else { }
w.Header().Set("Access-Control-Allow-Origin", "*")
} }
// Handle request. // Handle request.