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
Prevent `POST /api/session/reset_password` from accepting the same current password (#86023)
Rodrigo López Dato8d90abc8400a
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex ac482923c37..68109cde2af 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -2655,7 +2655,6 @@:api #{metabase.server.coremetabase.server.initmetabase.server.middleware.security- metabase.server.middleware.sessionmetabase.server.settingsmetabase.server.streaming-response} ; TODO -- too many API namespaces:uses #{analytics@@ -4562,7 +4561,6 @@lib.schemamodelspermissions- serversettingssystemusersdiff --git a/e2e/test/scenarios/onboarding/auth/forgot_password.cy.spec.js b/e2e/test/scenarios/onboarding/auth/forgot_password.cy.spec.jsindex 4a63381a90d..bf71c1d822b 100644--- a/e2e/test/scenarios/onboarding/auth/forgot_password.cy.spec.js+++ b/e2e/test/scenarios/onboarding/auth/forgot_password.cy.spec.js@@ -3,6 +3,8 @@ import { USERS } from "e2e/support/cypress_data";const { admin } = USERS;+const NEW_PASSWORD = `new-${admin.password}`;+describe("scenarios > auth > password", { tags: "@external" }, () => {beforeEach(() => {H.restore();@@ -24,8 +26,8 @@ describe("scenarios > auth > password", { tags: "@external" }, () => {H.getInbox().then(({ body: [{ html }] }) => {cy.visit(getResetLink(html));- cy.findByLabelText("Create a password").type(admin.password);- cy.findByLabelText("Confirm your password").type(admin.password);+ cy.findByLabelText("Create a password").type(NEW_PASSWORD);+ cy.findByLabelText("Confirm your password").type(NEW_PASSWORD);cy.findByText("Save new password").click();cy.findByText("You've updated your password.");diff --git a/enterprise/backend/src/metabase_enterprise/scim/auth.clj b/enterprise/backend/src/metabase_enterprise/scim/auth.cljindex cdb311c1f66..f8f4cef270a 100644--- a/enterprise/backend/src/metabase_enterprise/scim/auth.clj+++ b/enterprise/backend/src/metabase_enterprise/scim/auth.clj@@ -3,7 +3,6 @@[metabase-enterprise.scim.db :as scim.db][metabase-enterprise.scim.settings :as scim.settings][metabase.api.open-api :as open-api]- [metabase.server.middleware.session :as mw.session][metabase.util.password :as u.password]))(defn- validate-scim-api-key@@ -14,7 +13,7 @@(let [expected-api-key (-> (scim.db/scim-api-key) :key)](if (and api-key expected-api-key)(u.password/verify-password api-key "" expected-api-key)- (mw.session/do-useless-hash)))))+ (u.password/do-useless-hash)))))(def ^:private error-schema-uri "urn:ietf:params:scim:api:messages:2.0:Error")diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.cljindex 23e83d5f888..c7618d6a7db 100644--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj@@ -16,6 +16,7 @@[metabase.test :as mt][metabase.test.fixtures :as fixtures][metabase.util :as u]+ [metabase.util.password :as u.password][toucan2.core :as t2]));; :test-users is load-bearing, not boilerplate -- deactivating the support user is only legal while another admin@@ -484,3 +485,44 @@:set {:expires_at (t/minus (t/instant) (t/minutes 1))}:where [:= :id (:id session)]})(is (= "Unauthenticated" (mt/client session-key :get 401 "user/current"))))))))))++(deftest reset-password-grant-tokens-cost-same-bcrypt-work-test+ (testing "POST /api/session/reset_password and GET /api/session/password_reset_token_valid run the same number of bcrypt checks for grant users as for any other token that gets the same answer"+ (mt/with-temp [:model/User {creator-id :id} {}+ :model/User {grant-id :id} {}+ :model/User {both-id :id} {}+ :model/User {inactive-id :id} {}+ :model/User {reset-id :id} {}+ :model/SupportAccessGrantLog grant {:user_id creator-id+ :ticket_number "TEST-BCRYPT"+ :notes "Test bcrypt cost"+ :grant_start_timestamp (t/offset-date-time)+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))+ :revoked_at nil}]+ (sag.provider/create-support-access-reset! grant-id grant)+ (sag.provider/create-support-access-reset! both-id grant)+ (auth-identity/create-password-reset! both-id)+ (auth-identity/create-password-reset! reset-id)+ (let [inactive-token (sag.provider/create-support-access-reset! inactive-id grant)+ checks (atom 0)+ bcrypt (mt/original-fn #'u.password/bcrypt-verify)+ invalid-token {"malformed" "not-a-token"+ "wrong reset secret" (str reset-id "_" (random-uuid))+ "wrong grant secret" (str grant-id "_" (random-uuid))+ "wrong secret, grant + reset" (str both-id "_" (random-uuid))}+ cost (fn [f] (reset! checks 0) (f) @checks)]+ (t2/update! :model/User :id inactive-id {:is_active false})+ (mt/with-dynamic-fn-redefs [u.password/bcrypt-verify (fn [token hash] (swap! checks inc) (bcrypt token hash))]+ (testing "reset_password answering Invalid reset token"+ (let [costs (into {} (for [[label token] (assoc invalid-token "deactivated grant user" inactive-token)]+ [label (cost #(is (= {:errors {:password "Invalid reset token"}}+ (mt/client :post 400 "session/reset_password"+ {:token token :password "SomePassword12!!"}))))]))]+ (is (apply = (vals costs)) (pr-str costs))+ (is (not (t2/exists? :model/AuthIdentity :user_id inactive-id :provider "password"))+ "the deactivated grant user gets no password")))+ (testing "password_reset_token_valid answering false"+ (let [costs (into {} (for [[label token] (assoc invalid-token "deactivated grant user" inactive-token)]+ [label (cost #(is (= {:valid false}+ (mt/client :get 200 "session/password_reset_token_valid" :token token))))]))]+ (is (apply = (vals costs)) (pr-str costs)))))))))diff --git a/src/metabase/auth_identity/models/auth_identity.clj b/src/metabase/auth_identity/models/auth_identity.cljindex 35ac3aff61b..fb04f1d7c88 100644--- a/src/metabase/auth_identity/models/auth_identity.clj+++ b/src/metabase/auth_identity/models/auth_identity.clj@@ -128,6 +128,14 @@(auth-identity.db/delete-auth-identities! user-id "emailed-secret-password-reset")(auth-identity.db/end-sessions-for-user! user-id (:ended-by opts)))))+(mu/defn current-password? :- :boolean+ "Whether `password` is the current password of the user with `user-id`, false when they have none."+ [user-id :- ms/PositiveInt+ password :- :string]+ (boolean+ (when-let [{{:keys [password_hash password_salt]} :credentials} (auth-identity.db/auth-identity user-id "password")]+ (u.password/verify-password password password_salt password_hash))))+(mu/defn reset-token-hash :- [:maybe :string]"The bcrypt hash of `user-id`'s current password-reset token, taken from their `emailed-secret-password-reset`AuthIdentity (the authoritative store), or nil if they have none. Lets callers include the token in audit eventsdiff --git a/src/metabase/auth_identity/providers/emailed_secret.clj b/src/metabase/auth_identity/providers/emailed_secret.cljindex 1a592a819c3..98b6eacea62 100644--- a/src/metabase/auth_identity/providers/emailed_secret.clj+++ b/src/metabase/auth_identity/providers/emailed_secret.clj@@ -49,24 +49,20 @@:timestamp (t/instant)}})(mu/defn- verify-reset-token :- [:enum :valid :expired :consumed :invalid]- "Verifies a password reset token against stored credentials.-- Checks the `token` against the provided `credentials` map and returns one of:- - `:valid` if the token matches and hasn't expired or been consumed- - `:expired` if the token matches but has passed its expiration time- - `:consumed` if the token has already been used- - `:invalid` if the token doesn't match the stored hash"+ "Checks `token` against stored reset `credentials` with one bcrypt check, returning `:consumed`, `:expired`, `:valid`,+ or `:invalid`, in that order of precedence."[token :- :stringcredentials :- ::auth-identity.schema/auth-identity.credentials.token]- (cond- (:consumed_at credentials)- :consumed- (t/after? (t/instant) (:expires_at credentials))- :expired- (u.password/bcrypt-verify token (:token_hash credentials))- :valid- :else- :invalid))+ (let [matches? (u.password/bcrypt-verify token (:token_hash credentials))]+ (cond+ (:consumed_at credentials)+ :consumed+ (t/after? (t/instant) (:expires_at credentials))+ :expired+ matches?+ :valid+ :else+ :invalid)))(mu/defn mark-token-consumed :- ::auth-identity.schema/auth-identity"Marks a token as consumed by setting the `:consumed_at` timestamp in the auth-identity's credentials.@@ -77,12 +73,9 @@(assoc-in auth-identity [:credentials :consumed_at] (t/instant)))(mu/defn- parse-token-user-id :- [:maybe ms/PositiveInt]- "Extracts the user ID from a password reset token.-- Password reset tokens follow the format `USER-ID_RANDOM-UUID` (e.g., `123_abc-def-ghi`). Returns the user ID as an- integer if the token matches this format, or nil if the token format is invalid."+ "The positive user ID that starts a `USER-ID_RANDOM-UUID` reset token, or nil for any other token."[token :- :string]- (when-let [[_ user-id-str] (re-matches #"(^\d+)_.+$" token)]+ (when-let [[_ user-id-str] (re-matches #"^([1-9]\d*)_.+$" token)](try(Integer/parseInt user-id-str)(catch NumberFormatException _@@ -127,15 +120,9 @@;;; -------------------------------------------------- Multimethod Implementations --------------------------------------------------(methodical/defmethod provider/authenticate :provider/emailed-secret- "Authenticates a user using a password reset token.-- The request map should contain a `:token` key with a password reset token in the format `USER-ID_RANDOM-UUID`.- Validates the token by checking it against the stored [[AuthIdentity]] credentials, verifying it hasn't expired or- been consumed.-- Returns a map with `:success?` true and `:user-id` and `:auth-identity` on success, or `:success?` false with an- `:error` keyword (`:invalid-token`, `:expired-token`, `:consumed-token`, `:no-auth-identity`, or `:server-error`)- and human-readable `:message` on failure."+ "Authenticates `:token` for an active user against their stored reset token, spending one bcrypt check on every+ token, and fails with `:invalid-request`, `:invalid-token`, `:expired-token`, `:consumed-token`,+ `:no-auth-identity`, `:inactive-user`, or `:server-error`."[provider {:keys [token]}](log/debug "Authenticating with emailed_secret provider for token")(cond@@ -150,11 +137,15 @@(let [verification-result (verify-reset-token token (:credentials auth-identity))](case verification-result:valid- (do- (log/debugf "Valid reset token for user %s" user-id)- {:success? true- :user-id user-id- :auth-identity auth-identity})+ (if (auth-identity.db/user-active? user-id)+ (do+ (log/debugf "Valid reset token for user %s" user-id)+ {:success? true+ :user-id user-id+ :auth-identity auth-identity})+ {:success? false+ :error :inactive-user+ :message "Reset token belongs to an inactive user"}):expired{:success? false:error :expired-token@@ -167,12 +158,14 @@{:success? false:error :invalid-token:message "Reset token is invalid"}))- {:success? false- :error :no-auth-identity- :message "No reset token found for this user"})- {:success? false- :error :invalid-token- :message "Invalid token format"})+ (do (u.password/do-useless-hash)+ {:success? false+ :error :no-auth-identity+ :message "No reset token found for this user"}))+ (do (u.password/do-useless-hash)+ {:success? false+ :error :invalid-token+ :message "Invalid token format"}))(catch Exception e(log/errorf "Unexpected error during reset token verification: %s" (ex-message e)){:success? false@@ -180,16 +173,20 @@:message "An unexpected error occurred during token verification"}))))(methodical/defmethod provider/login! :after :provider/emailed-secret-password-reset- "Completes the password reset process after successful authentication.-- After a successful password reset authentication, this method:- - Publishes a password reset event or sends admin notification (for new users)- - Updates the user's password, which also removes the now-used reset token (see- [[metabase.auth-identity.core/set-password!]])- - Points the session the login is about to create at the user's `password` AuthIdentity."+ "Refuses a new password equal to the current one with `:password-unchanged`, changing nothing; otherwise records the+ reset, sets the password (which deletes the reset token), and points the new session at the `password` identity."[_provider {:keys [user password] :as result}]- (if-not (:success? result)+ (cond+ (not (:success? result))result++ (auth-identity/current-password? (:id user) password)+ (assoc result+ :success? false+ :error :password-unchanged+ :message "New password must be different from your current password.")++ :else(do(if (:last_login user)(events/publish-event! :event/password-reset-successful {:object (assoc user :token (auth-identity/reset-token-hash (:id user)))})diff --git a/src/metabase/auth_identity/providers/password.clj b/src/metabase/auth_identity/providers/password.cljindex d61e1c26db3..6be8533e10b 100644--- a/src/metabase/auth_identity/providers/password.clj+++ b/src/metabase/auth_identity/providers/password.clj@@ -20,10 +20,6 @@;;; -------------------------------------------------- Multimethod Implementations ---------------------------------------------------;; Fake salt & hash used to run bcrypt hash if user doesn't exist, to avoid timing attacks (Metaboat #134)-(def ^:private fake-salt "ee169694-5eb6-4010-a145-3557252d7807")-(def ^:private fake-hashed-password "$2a$10$owKjTym0ZGEEZOpxM0UyjekSvt66y1VvmOJddkAaMB37e0VAIVOX2")-(methodical/defmethod provider/validate :provider/password"Validate password credentials before insert/update into AuthIdentity.Ensures password_hash and password_salt are present."@@ -86,7 +82,7 @@:error :invalid-credentials:message "Password did not match stored password."}));; Still run bcrypt to prevent timing attacks- (do (u.password/verify-password password fake-salt fake-hashed-password)+ (do (u.password/do-useless-hash){:success? false:error :invalid-credentials:message "No user found with that email address."}))))diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex 465ef5328d0..488576f354a 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -128,15 +128,6 @@(assoc :metabase/authed-session-key-hash session-key-hash:embedding/auth-method (or auth-provider "session")))))))-(def ^:private api-key-that-should-never-match (str (random-uuid)))-(def ^:private hash-that-should-never-match (u.password/hash-bcrypt "password"))--(defn do-useless-hash- "Password check that will always fail, used to avoid exposing any info about existing users or API keys via timing- attacks."- []- (u.password/verify-password api-key-that-should-never-match "" hash-that-should-never-match))-(defn- matching-api-key?"Whether `passed-api-key` matches the hash stored in `user-data`. The stored bcrypt hash is encrypted at rest and thispath reads the raw column (bypassing the model's decrypting transform), so it is decrypted before the bcrypt compare;@@ -147,7 +138,7 @@(if-let [stored-hash (when api-key(u/ignore-exceptions (encryption/maybe-decrypt api-key)))](u.password/verify-password passed-api-key "" stored-hash)- (do-useless-hash)))+ (u.password/do-useless-hash)))(mu/defn- current-user-info-for-api-key :- [:maybe ::request.schema/current-user-info]"Return User ID and superuser status for an API Key with `api-key-id"diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.cljindex b26b5531289..4cbcc255079 100644--- a/src/metabase/session/api.clj+++ b/src/metabase/session/api.clj@@ -431,6 +431,10 @@[:provider/emailed-secret-password-reset]credentials))](cond+ (= :password-unchanged (:error auth-result))+ (api/throw-invalid-param-exception+ :password (tru "New password must be different from your current password."))+(not (:success? auth-result))(api/throw-invalid-param-exception :password (tru "Invalid reset token"))diff --git a/src/metabase/util/password.clj b/src/metabase/util/password.cljindex 2c4dfc965e3..e8831a77abb 100644--- a/src/metabase/util/password.clj+++ b/src/metabase/util/password.clj@@ -121,3 +121,11 @@ the result of previously hashing that password.";; we wrap the friend/bcrypt-verify with this function specifically to avoid unintended exceptions getting out(boolean (u/ignore-exceptions(bcrypt-verify (str salt password) hashed-password))))++(def ^:private secret-that-should-never-match (str (random-uuid)))+(def ^:private hash-that-should-never-match (hash-bcrypt "password"))++(defn do-useless-hash+ "Runs one bcrypt check that always fails, so a request with nothing to check takes as long as one that has."+ []+ (verify-password secret-that-should-never-match "" hash-that-should-never-match))diff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.cljindex b31de8833bd..5c0b038c8da 100644--- a/test/metabase/session/api_test.clj+++ b/test/metabase/session/api_test.clj@@ -3,6 +3,7 @@(:require[clj-http.client :as http][clojure.test :refer :all]+ [java-time.api :as t][medley.core :as m][metabase.appearance.core :as appearance][metabase.auth-identity.core :as auth-identity]@@ -27,6 +28,7 @@[metabase.util.json :as json][metabase.util.jvm :as u.jvm][metabase.util.malli.schema :as ms]+ [metabase.util.password :as u.password][metabase.util.string :as string][toucan2.core :as t2]))@@ -609,6 +611,81 @@(is (nil? (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "emailed-secret-password-reset"))"the consumed reset identity is still deleted"))))))+(deftest reset-password-refuses-current-password-test+ (testing "POST /api/session/reset_password refuses, and changes nothing, when the new password is the current one"+ (mt/with-temp [:model/User user {}]+ (auth-identity/set-password! (:id user) "whateverUP12!!")+ (let [token (auth-identity/create-password-reset! (:id user))]+ (is (= {:errors {:password "New password must be different from your current password."}}+ (mt/client :post 400 "session/reset_password" {:token token :password "whateverUP12!!"})))+ (is (some? (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "emailed-secret-password-reset"))+ "the reset token is not consumed, so the user can retry with a different password")+ (is (=? {:success true}+ (mt/client :post 200 "session/reset_password" {:token token :password "somethingElseUP12!!"})))))))++(deftest reset-password-bad-tokens-cost-same-bcrypt-work-test+ (testing "POST /api/session/reset_password and GET /api/session/password_reset_token_valid run the same number of bcrypt checks for every token that gets the same answer"+ (mt/with-temp [:model/User {idle-id :id} {}+ :model/User {pending-id :id} {}+ :model/User {expired-id :id} {}+ :model/User {inactive-id :id} {}]+ (auth-identity/create-password-reset! pending-id)+ (let [expired-token (auth-identity/create-password-reset! expired-id)+ inactive-token (auth-identity/create-password-reset! inactive-id)+ expired-ai (t2/select-one :model/AuthIdentity :user_id expired-id :provider "emailed-secret-password-reset")+ checks (atom 0)+ bcrypt (mt/original-fn #'u.password/bcrypt-verify)+ invalid-token {"malformed" "not-a-token"+ "zero user id" "0_abc"+ "no pending reset" (str idle-id "_" (random-uuid))+ "wrong secret" (str pending-id "_" (random-uuid))+ "expired" expired-token}+ cost (fn [f] (reset! checks 0) (f) @checks)]+ (t2/update! :model/AuthIdentity :id (:id expired-ai)+ {:credentials (assoc (:credentials expired-ai) :expires_at (t/minus (t/instant) (t/days 1)))})+ (t2/update! :model/User :id inactive-id {:is_active false})+ (mt/with-dynamic-fn-redefs [u.password/bcrypt-verify (fn [token hash] (swap! checks inc) (bcrypt token hash))]+ (testing "reset_password answering Invalid reset token"+ (let [costs (into {} (for [[label token] (assoc invalid-token "deactivated user" inactive-token)]+ [label (cost #(is (= {:errors {:password "Invalid reset token"}}+ (mt/client :post 400 "session/reset_password"+ {:token token :password "SomePassword12!!"}))))]))]+ (is (apply = (vals costs)) (pr-str costs))))+ (testing "password_reset_token_valid answering false"+ (let [costs (into {} (for [[label token] (assoc invalid-token "deactivated user" inactive-token)]+ [label (cost #(is (= {:valid false}+ (mt/client :get 200 "session/password_reset_token_valid" :token token))))]))]+ (is (apply = (vals costs)) (pr-str costs)))))))))++(deftest reset-password-changes-nothing-for-deactivated-user-test+ (testing "POST /api/session/reset_password answers like an invalid token, and changes nothing, for a user deactivated after the token was sent"+ (mt/with-temp [:model/User user {}]+ (auth-identity/set-password! (:id user) "currentPassUP12!!")+ (let [token (auth-identity/create-password-reset! (:id user))]+ (t2/update! :model/User :id (:id user) {:is_active false})+ (doseq [password ["currentPassUP12!!" "somethingElseUP12!!"]]+ (testing password+ (is (= {:errors {:password "Invalid reset token"}}+ (mt/client :post 400 "session/reset_password" {:token token :password password})))))+ (is (:success? (auth-identity/authenticate :provider/password {:email (:email user) :password "currentPassUP12!!"}))+ "the current password still works")+ (is (some? (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "emailed-secret-password-reset"))+ "the reset token is not consumed")))))++(deftest reset-password-compares-against-token-user-after-email-change-test+ (testing "POST /api/session/reset_password compares with the password of the token's user, not of whoever now has the email the token was sent to"+ (mt/with-temp [:model/User user {:email "[email protected]"}+ :model/User other {:email "[email protected]"}]+ (auth-identity/set-password! (:id user) "ownerPassUP12!!")+ (auth-identity/set-password! (:id other) "otherPassUP12!!")+ (let [token (auth-identity/create-password-reset! (:id user))]+ (t2/update! :model/User :id (:id user) {:email "[email protected]"})+ (t2/update! :model/User :id (:id other) {:email "[email protected]"})+ (is (= {:errors {:password "New password must be different from your current password."}}+ (mt/client :post 400 "session/reset_password" {:token token :password "ownerPassUP12!!"})))+ (is (=? {:success true}+ (mt/client :post 200 "session/reset_password" {:token token :password "otherPassUP12!!"})))))))+(deftest reset-password-refused-when-password-login-disabled-test(testing "POST /api/session/reset_password refuses, and changes nothing, when password login is disabled"(ldap.test/with-ldap-server!