From 2816780b520b444f42e764ebe4a02a1c6906fc71 Mon Sep 17 00:00:00 2001 From: Jakob Borg Date: Fri, 27 Aug 2021 17:56:54 +0200 Subject: [PATCH] lib/api: Set "Secure" on session cookies served over HTTPS (ref #7399) (#7907) So that it does not unnecessarily leak over clear text connections. --- lib/api/api_auth.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/api/api_auth.go b/lib/api/api_auth.go index 70078111d..5a009c5db 100644 --- a/lib/api/api_auth.go +++ b/lib/api/api_auth.go @@ -108,10 +108,22 @@ func basicAuthAndSessionMiddleware(cookieName string, guiCfg config.GUIConfigura sessionsMut.Lock() sessions[sessionid] = true sessionsMut.Unlock() + + // Best effort detection of whether the connection is HTTPS -- + // either directly to us, or as used by the client towards a reverse + // proxy who sends us headers. + connectionIsHTTPS := r.TLS != nil || + strings.ToLower(r.Header.Get("x-forwarded-proto")) == "https" || + strings.Contains(strings.ToLower(r.Header.Get("forwarded")), "proto=https") + // If the connection is HTTPS, or *should* be HTTPS, set the Secure + // bit in cookies. + useSecureCookie := connectionIsHTTPS || guiCfg.UseTLS() + http.SetCookie(w, &http.Cookie{ Name: cookieName, Value: sessionid, MaxAge: 0, + Secure: useSecureCookie, }) emitLoginAttempt(true, username, r.RemoteAddr, evLogger)