The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Sign session key hashes with a server-side secret (#80046)
bryan9450affe98c9
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj b/enterprise/backend/src/metabase_enterprise/sso/api/sso.cljindex 9a6ce477244..bb1bfae6aaa 100644--- a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj@@ -106,12 +106,11 @@(t2/query-one {:select [:u.email :u.sso_source]:from [[:core_user :u]]:join [[:core_session :session] [:= :u.id :session.user_id]]- :where [:or [:= :key_hashed metabase-session-key-hashed] [:= :session.id metabase-session-key]]})]+ :where [:= :key_hashed metabase-session-key-hashed]})];; If a user doesn't have SLO setup on their IdP,;; they will never hit "/handle_slo" so we must delete the session here:- ;; NOTE: Only safe to compare the plaintext session-key to core_session.id because of the call to `validate-session-key` above(when-not (sso-settings/saml-slo-enabled)- (t2/delete! :model/Session {:where [:or [:= :key_hashed metabase-session-key-hashed] [:= :id metabase-session-key]]}))+ (t2/delete! :model/Session :key_hashed metabase-session-key-hashed)){:saml-logout-url(when (and (sso-settings/saml-slo-enabled)(= sso_source "saml"))diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.cljindex 761a8850ade..c1a0b5f5ef9 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj@@ -231,7 +231,7 @@:response-validators [:signature :require-authenticated :issuer]})](if-let [metabase-session-key (and (saml/logout-success? response) (get-in cookies [request/metabase-session-cookie :value]))](do- (t2/delete! :model/Session {:where [:or [:= (session/hash-session-key metabase-session-key) :key_hashed] [:= metabase-session-key :id]]})+ (t2/delete! :model/Session :key_hashed (session/hash-session-key metabase-session-key))(request/clear-session-cookie (response/redirect (system/site-url)))){:status 500 :body "SAML logout failed."}))(log/warn "SAML SLO is not enabled, not continuing Single Log Out flow.")))diff --git a/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.clj b/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.cljindex d37e88b0063..64e35b9317e 100644--- a/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.clj@@ -31,11 +31,12 @@saml-identity-provider-slo-uri "http://idp.example.com/logout"](mt/with-dynamic-fn-redefs [random-uuid (constantly "66d96ab4-9834-40db-a3cd-42b361503ab9")](binding [client/*url-prefix* ""]- (mt/with-temp [:model/User user {:email "[email protected]" :sso_source "saml"}- :model/Session {session-id :id} {:user_id (:id user) :id (session/generate-session-id) :key_hashed (session/hash-session-key (session/generate-session-key))}]- (let [req-options (assoc-in {} [:request-options :cookies request/metabase-session-cookie :value] session-id)]+ (let [session-key (session/generate-session-key)]+ (mt/with-temp [:model/User user {:email "[email protected]" :sso_source "saml"}+ :model/Session _ {:user_id (:id user) :id (session/generate-session-id) :key_hashed (session/hash-session-key session-key)}](testing "logout is redirected to idp"- (let [response (client/client :post "/auth/sso/logout" req-options)]+ (let [req-options (assoc-in {} [:request-options :cookies request/metabase-session-cookie :value] session-key)+ response (client/client :post "/auth/sso/logout" req-options)](is (= (str"http://idp.example.com/logout?SAMLRequest=nZFBa4Qw""EIXv%2FRWSezQa165B3RakIOz20G576KVEDduASawTy%2F78Rl"diff --git a/src/metabase/cmd/resources/other-env-vars.md b/src/metabase/cmd/resources/other-env-vars.mdindex 087134f2772..30d6e1ee49e 100644--- a/src/metabase/cmd/resources/other-env-vars.md+++ b/src/metabase/cmd/resources/other-env-vars.md@@ -494,6 +494,13 @@ Default: `"db"`Current cache backend. Dynamically rebindable primarily for test purposes.+### `MB_SESSION_SECRET_KEY`++Type: string<br>+Default: `null`++When set, session keys are stored in the application database signed with this secret, so a valid session cannot be created or used with database access alone. Requirement: minimum 16 characters. Setting or changing this value logs out all active sessions.+### `MB_SETUP_TOKEN`Type: string<br>diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex 2710bf96eba..41a4cce0b7f 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -130,7 +130,7 @@[:or [:= :tenant.id nil] :tenant.is_active][:= :tenant.id nil])[:= :user.is_active true]- [:or [:= :session.id ^:allow-raw-sql [:raw "?"]] [:= :session.key_hashed ^:allow-raw-sql [:raw "?"]]]+ [:= :session.key_hashed ^:allow-raw-sql [:raw "?"]][:> :session.created_at (oldest-allowed-expr db-type max-age-minutes :minute)][:= :session.anti_csrf_token (case session-type:normal nil@@ -201,11 +201,8 @@[:is :pgm.is_group_manager true]]))))))))(defn- valid-session-key?- "Validates that the given session-key looks like it could be a session id. Returns a 403 if it does not.-- SECURITY NOTE: Because functions will directly compare the session-key against the core_session.id table for- backwards-compatibility reasons, if this is NOT called before those queries against core_session.id, attackers with- access to the database can impersonate users by passing the core_session.id as their session cookie"+ "Validates that the given session-key looks like a session key (a UUID string). Session keys are only ever compared+ against `core_session.key_hashed`; this check short-circuits obviously-invalid values before we hash them."[session-key](or (not session-key) (string/valid-uuid? session-key)))@@ -221,7 +218,7 @@(and (premium-features/enable-tenants?)(setting/get :use-tenants))timeout)- params (concat [session-key (session/hash-session-key session-key)]+ params (concat [(session/hash-session-key session-key)](when (seq anti-csrf-token)[anti-csrf-token]))](some-> (t2/query-one (cons sql params))diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.cljindex b381c688ce6..eda21051c09 100644--- a/src/metabase/session/api.clj+++ b/src/metabase/session/api.clj@@ -220,9 +220,13 @@[_route-params _query-params _body {:keys [metabase-session-key], :as _request}](api/check-404 (not-empty metabase-session-key))(let [session-key-hashed (session/hash-session-key metabase-session-key)- rows-deleted (t2/delete! :model/Session {:where [:or [:= :key_hashed session-key-hashed] [:= :id metabase-session-key]]})]- (api/check-404 (> rows-deleted 0))- (request/clear-session-cookie api/generic-204-no-content)))+ rows-deleted (t2/delete! :model/Session :key_hashed session-key-hashed)]+ ;; clear the cookie even when no row matched (e.g. a session hashed under a previous secret), or the browser+ ;; would keep resending the dead cookie+ (request/clear-session-cookie+ (if (pos? rows-deleted)+ api/generic-204-no-content+ {:status 404, :body "Not found."}))));; Reset tokens: We need some way to match a plaintext token with the a user since the token stored in the DB is;; hashed. So we'll make the plaintext token in the format USER-ID_RANDOM-UUID, e.g.diff --git a/src/metabase/session/models/session.clj b/src/metabase/session/models/session.cljindex eb514e68705..9ec8b698229 100644--- a/src/metabase/session/models/session.clj+++ b/src/metabase/session/models/session.clj@@ -2,13 +2,17 @@(:require[buddy.core.codecs :as codecs][buddy.core.hash :as buddy-hash]+ [buddy.core.mac :as mac][buddy.core.nonce :as nonce][clojure.core.memoize :as memo]+ [environ.core :as env][metabase.events.core :as events][metabase.request.core :as request][metabase.session.settings :as session.settings][metabase.util :as u]+ [metabase.util.encryption :as encryption][metabase.util.i18n :refer [tru]]+ [metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.string :as string][methodical.core :as methodical]@@ -20,9 +24,39 @@[](codecs/bytes->hex (nonce/random-bytes 16)))-(def ^{:arglists '([session-key])} hash-session-key- "Hash the session-key for storage in the database"- (memo/lru (fn [^String session-key] (codecs/bytes->hex (buddy-hash/sha512 (.getBytes session-key java.nio.charset.StandardCharsets/US_ASCII)))) {} :lru/threshold 100))+;; validated eagerly at load so a misconfigured secret fails at startup instead of 500ing the first auth request+(defonce ^:private ^{:tag 'bytes} default-session-hash-secret+ (encryption/validate-and-hash-secret-key (env/env :mb-session-secret-key) "MB_SESSION_SECRET_KEY"))++(when-not *compile-files*+ (when-not default-session-hash-secret+ (log/warn (str "MB_SESSION_SECRET_KEY is not set; session keys are stored without a signature. Anyone with access"+ " to the application database can forge a session and impersonate any user. Set it to a random"+ " string of at least 16 characters to prevent this. Setting or changing it logs out all active"+ " sessions."))))++(defn- session-hash-secret+ "Secret used to sign session keys before they are stored in or looked up from the app DB. Read from+ `MB_SESSION_SECRET_KEY`. Nil when it is not set."+ ^bytes []+ default-session-hash-secret)++(def ^:private ^{:arglists '([secret session-key])} hash-session-key*+ (memo/lru (fn [^bytes secret ^String session-key]+ (let [key-bytes (.getBytes session-key java.nio.charset.StandardCharsets/US_ASCII)]+ (codecs/bytes->hex+ (if secret+ (mac/hash key-bytes {:key secret :alg :hmac+sha512})+ (buddy-hash/sha512 key-bytes)))))+ {} :lru/threshold 100))++(defn hash-session-key+ "Hash the session-key for storage in (and lookup from) the database.++ When `MB_SESSION_SECRET_KEY` is set the stored value is signed with that secret (HMAC-SHA512), so a valid+ `key_hashed` value cannot be computed with app-db (SQL) access alone. Without it this is a plain SHA-512."+ [session-key]+ (hash-session-key* (session-hash-secret) session-key))(defn generate-session-key"Generate a new session key."diff --git a/src/metabase/util/encryption.clj b/src/metabase/util/encryption.cljindex 3ad2c973791..b6fd065a646 100644--- a/src/metabase/util/encryption.clj+++ b/src/metabase/util/encryption.clj@@ -40,13 +40,16 @@64))(defn validate-and-hash-secret-key- "Check the minimum length of the key and hash it for internal usage."- [^String secret-key]- (when-let [secret-key secret-key]- (when (seq secret-key)- (assert (>= (count secret-key) 16)- (str (trs "MB_ENCRYPTION_SECRET_KEY must be at least 16 characters.")))- (secret-key->hash secret-key))))+ "Check the minimum length of the key and hash it for internal usage. Returns nil for a blank key. `env-var-name` names+ the source in the length-assertion message."+ ([^String secret-key]+ (validate-and-hash-secret-key secret-key "MB_ENCRYPTION_SECRET_KEY"))+ ([^String secret-key env-var-name]+ (when-let [secret-key secret-key]+ (when (seq secret-key)+ (assert (>= (count secret-key) 16)+ (str (trs "{0} must be at least 16 characters." env-var-name)))+ (secret-key->hash secret-key)))));; apparently if you're not tagging in an arglist, `^bytes` will set the `:tag` metadata to `clojure.core/bytes` (ick);; so you have to do `^{:tag 'bytes}` insteaddiff --git a/test/metabase/session/models/session_test.clj b/test/metabase/session/models/session_test.cljindex db27a0ccbe0..e365461f021 100644--- a/test/metabase/session/models/session_test.clj+++ b/test/metabase/session/models/session_test.clj@@ -1,5 +1,8 @@(ns metabase.session.models.session-test(:require+ [buddy.core.codecs :as codecs]+ [buddy.core.hash :as buddy-hash]+ [buddy.core.mac :as mac][clojure.string :as str][clojure.test :refer :all][java-time.api :as t]@@ -14,6 +17,8 @@[metabase.util.malli.schema :as ms][toucan2.core :as t2]))+(set! *warn-on-reflection* true)+(use-fixtures :once (fixtures/initialize :db :test-users))(def ^:private test-uuid #uuid "092797dd-a82a-4748-b393-697d7bb9ab65")@@ -168,10 +173,25 @@(is (nil? (:key session)) "Key is not returned by the insert")(is (= (session/hash-session-key key) (t2/select-one-fn :key_hashed :model/Session :user_id user-id)))))))-(deftest ^:parallel hash-session-key-test- (is (= "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff"- (session/hash-session-key "test")))- (is (= "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff"- (session/hash-session-key "test")))- (is (= "6d201beeefb589b08ef0672dac82353d0cbd9ad99e1642c83a1601f3d647bcca003257b5e8f31bdc1d73fbec84fb085c79d6e2677b7ff927e823a54e789140d9"- (session/hash-session-key "test2"))))+(deftest hash-session-key-test+ (testing "the no-secret on-disk format stays plain SHA-512; a format regression here mass-logs-out keyless+ deployments on upgrade"+ (with-redefs-fn {#'session/session-hash-secret (constantly nil)}+ (fn []+ (is (= "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff"+ (session/hash-session-key "test")))+ (is (= "6d201beeefb589b08ef0672dac82353d0cbd9ad99e1642c83a1601f3d647bcca003257b5e8f31bdc1d73fbec84fb085c79d6e2677b7ff927e823a54e789140d9"+ (session/hash-session-key "test2")))))))++(deftest keyed-hash-session-key-test+ (testing "with a configured secret, key_hashed is an HMAC and not derivable from the session key alone"+ (let [secret (byte-array (range 64))+ ^String session-key (str (random-uuid))+ key-bytes (.getBytes session-key java.nio.charset.StandardCharsets/US_ASCII)]+ (with-redefs-fn {#'session/session-hash-secret (constantly secret)}+ (fn []+ (is (= (codecs/bytes->hex (mac/hash key-bytes {:key secret :alg :hmac+sha512}))+ (session/hash-session-key session-key)))+ (is (not= (codecs/bytes->hex (buddy-hash/sha512 key-bytes))+ (session/hash-session-key session-key))+ "keyed hash must differ from the unsalted SHA-512 an attacker can compute"))))))