From b86c9fa8febe68529941b6d9788421503db94c78 Mon Sep 17 00:00:00 2001 From: kermieisinthehouse Date: Mon, 13 Dec 2021 03:54:19 +0000 Subject: [PATCH] Security Hardening: Content Security Policy + more (#2108) * Add CSP, varied security headers --- pkg/api/server.go | 23 +++++++++++++++++++++++ ui/v2.5/index.html | 4 ++-- ui/v2.5/src/index.html.ejs | 11 ----------- ui/v2.5/src/locales/en-GB.json | 2 +- 4 files changed, 26 insertions(+), 14 deletions(-) delete mode 100644 ui/v2.5/src/index.html.ejs diff --git a/pkg/api/server.go b/pkg/api/server.go index a29ddd85c..8ec8333bf 100644 --- a/pkg/api/server.go +++ b/pkg/api/server.go @@ -54,6 +54,7 @@ func Start(uiBox embed.FS, loginUIBox embed.FS) { if c.GetLogAccess() { r.Use(middleware.Logger) } + r.Use(SecurityHeadersMiddleware) r.Use(middleware.DefaultCompress) r.Use(middleware.StripSlashes) r.Use(cors.AllowAll().Handler) @@ -342,6 +343,28 @@ var ( BaseURLCtxKey = &contextKey{"BaseURL"} ) +func SecurityHeadersMiddleware(next http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + c := config.GetInstance() + connectableOrigins := "connect-src data: 'self'" + if !c.IsNewSystem() && c.GetHandyKey() != "" { + connectableOrigins += " https://www.handyfeeling.com" + } + connectableOrigins += "; " + + cspDirectives := "default-src data: 'self' 'unsafe-inline';" + connectableOrigins + "script-src 'self' 'unsafe-inline'; child-src 'none'; object-src 'none'; form-action 'none'" + + w.Header().Set("Referrer-Policy", "same-origin") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("X-XSS-Protection", "1") + w.Header().Set("Content-Security-Policy", cspDirectives) + + next.ServeHTTP(w, r) + } + return http.HandlerFunc(fn) +} + func BaseURLMiddleware(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() diff --git a/ui/v2.5/index.html b/ui/v2.5/index.html index 3ef197643..dd15fa776 100755 --- a/ui/v2.5/index.html +++ b/ui/v2.5/index.html @@ -6,9 +6,9 @@ - +