Skip to content
Permalink
Browse files Browse the repository at this point in the history
Added a simple Content-Security-Policy to mitigate clickjacking attem…
…pts.
  • Loading branch information
jordan-wright committed Aug 20, 2020
1 parent e3352f4 commit 6df62e8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion controllers/route.go
Expand Up @@ -155,7 +155,7 @@ func (as *AdminServer) registerRoutes() {
csrf.FieldName("csrf_token"),
csrf.Secure(as.config.UseTLS))
adminHandler := csrfHandler(router)
adminHandler = mid.Use(adminHandler.ServeHTTP, mid.CSRFExceptions, mid.GetContext)
adminHandler = mid.Use(adminHandler.ServeHTTP, mid.CSRFExceptions, mid.GetContext, mid.ApplySecurityHeaders)

// Setup GZIP compression
gzipWrapper, _ := gziphandler.NewGzipLevelHandler(gzip.BestCompression)
Expand Down
11 changes: 11 additions & 0 deletions middleware/middleware.go
Expand Up @@ -176,6 +176,17 @@ func RequirePermission(perm string) func(http.Handler) http.HandlerFunc {
}
}

// ApplySecurityHeaders applies various security headers according to best-
// practices.
func ApplySecurityHeaders(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
csp := "frame-ancestors 'none';"
w.Header().Set("Content-Security-Policy", csp)
w.Header().Set("X-Frame-Options", "DENY")
next.ServeHTTP(w, r)
}
}

// JSONError returns an error in JSON format with the given
// status code and message
func JSONError(w http.ResponseWriter, c int, m string) {
Expand Down
16 changes: 16 additions & 0 deletions middleware/middleware_test.go
Expand Up @@ -181,3 +181,19 @@ func TestPasswordResetRequired(t *testing.T) {
t.Fatalf("incorrect location header received. expected %s got %s", expectedLocation, gotLocation)
}
}

func TestApplySecurityHeaders(t *testing.T) {
expected := map[string]string{
"Content-Security-Policy": "frame-ancestors 'none';",
"X-Frame-Options": "DENY",
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
response := httptest.NewRecorder()
ApplySecurityHeaders(successHandler).ServeHTTP(response, req)
for header, value := range expected {
got := response.Header().Get(header)
if got != value {
t.Fatalf("incorrect security header received for %s: expected %s got %s", header, value, got)
}
}
}

1 comment on commit 6df62e8

@abergmann
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CVE-2020-24711 was assigned to this commit.

Please sign in to comment.