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
Keep the CSP nonce out of the DOM, and off script-src (#82161)
Romeo Van Snick9762d0e16447
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml_utils.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml_utils.cljindex 3fba859ee3c..39ca0f51296 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml_utils.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml_utils.clj@@ -2,6 +2,7 @@"Functions for handling SAML authentication with the SDK side, including HTML popups"(:require[java-time.api :as t]+ [metabase.server.middleware.security :as mw.security][metabase.util.json :as json])(:import(java.time Instant)))@@ -49,10 +50,13 @@</html>"))(defn create-token-response- "Create a token response with HTML and JavaScript to post the auth message"+ "Create a token response with HTML and JavaScript to post the auth message. The inline script carries the+ session key and timestamps, so it varies per request and no build-time hash can cover it. The response+ opts into a `script-src` nonce for that reason."[session origin continue-url nonce](let [current-time (t/instant)expiration-time (t/plus current-time (t/seconds 86400))]{:status 200:headers {"Content-Type" "text/html"}+ mw.security/script-nonce-response-key true:body (generate-saml-html-popup (:key session) expiration-time current-time origin continue-url nonce)}))diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_utils_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_utils_test.cljindex 38c46d09d7d..a8feb90e016 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_utils_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_utils_test.clj@@ -3,6 +3,7 @@[clojure.string :as str][clojure.test :refer :all][metabase-enterprise.sso.integrations.saml-utils :as saml-utils]+ [metabase.server.middleware.security :as mw.security][metabase.util.json :as json]))(set! *warn-on-reflection* true)@@ -17,7 +18,9 @@(is (= 200 (:status response)))(is (= "text/html" (get-in response [:headers "Content-Type"])))(is (str/includes? (:body response)- (str "<script nonce=\"" nonce "\">"))))))+ (str "<script nonce=\"" nonce "\">")))+ (testing "and opts into a script-src nonce, since the script body varies per request"+ (is (true? (get response mw.security/script-nonce-response-key)))))))(deftest ^:parallel popup-values-are-json-encoded-test(testing "the popup script uses JSON-encoded values"diff --git a/resources/frontend_client/data_app_template.html b/resources/frontend_client/data_app_template.htmlindex 1c0a30addf3..fa8d8976123 100644--- a/resources/frontend_client/data_app_template.html+++ b/resources/frontend_client/data_app_template.html@@ -30,12 +30,10 @@{{{userColorScheme}}}</script>- <script type="application/json" id="_metabaseNonce">- {{{nonceJSON}}}- </script>-<!-- If you modify this script, make sure you update the whitelisted Content-Security-Policy hash in metabase.server.middleware.security -->- <script type="text/javascript">{{{bootstrapJS}}}</script>+ <!-- The nonce is here so index_bootstrap.js can read it off `document.currentScript.nonce`.+ The browser blanks the attribute after parsing, so the value stays out of the DOM. -->+ <script type="text/javascript" nonce="{{{nonce}}}">{{{bootstrapJS}}}</script><script type="text/javascript">{{{assetOnErrorJS}}}</script></head>diff --git a/resources/frontend_client/index_template.html b/resources/frontend_client/index_template.htmlindex e967250fddd..65bf1c84e0b 100644--- a/resources/frontend_client/index_template.html+++ b/resources/frontend_client/index_template.html@@ -45,12 +45,10 @@{{{userColorScheme}}}</script>- <script type="application/json" id="_metabaseNonce">- {{{nonceJSON}}}- </script>-<!-- If you modify this script, make sure you update the whitelisted Content-Security-Policy hash in metabase.server.middleware.security -->- <script type="text/javascript">{{{bootstrapJS}}}</script>+ <!-- The nonce is here so index_bootstrap.js can read it off `document.currentScript.nonce`.+ The browser blanks the attribute after parsing, so the value stays out of the DOM. -->+ <script type="text/javascript" nonce="{{{nonce}}}">{{{bootstrapJS}}}</script><script type="text/javascript">{{{assetOnErrorJS}}}</script></head>diff --git a/resources/frontend_client/inline_js/index_bootstrap.js b/resources/frontend_client/inline_js/index_bootstrap.jsindex 4de7fc32b26..81f33bae477 100644--- a/resources/frontend_client/inline_js/index_bootstrap.js+++ b/resources/frontend_client/inline_js/index_bootstrap.js@@ -3,7 +3,9 @@window.MetabaseUserLocalization = JSON.parse(document.getElementById("_metabaseUserLocalization").textContent);window.MetabaseSiteLocalization = JSON.parse(document.getElementById("_metabaseSiteLocalization").textContent);window.MetabaseUserColorScheme = JSON.parse(document.getElementById("_metabaseUserColorScheme").textContent);- window.MetabaseNonce = JSON.parse(document.getElementById("_metabaseNonce").textContent);+ // Read from the script element, not from a JSON block: the browser blanks a nonce content attribute+ // after parsing, so the value never stays readable in the DOM.+ window.MetabaseNonce = document.currentScript.nonce || "";var configuredRoot = document.head.querySelector("meta[name='base-href']").content;var actualRoot = "/";diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.cljindex 58fafefe479..ddd01a27ba0 100644--- a/src/metabase/server/middleware/security.clj+++ b/src/metabase/server/middleware/security.clj@@ -25,10 +25,18 @@(set! *warn-on-reflection* true)+(def script-nonce-response-key+ "Response key that opts a response into a `script-src` nonce. Set it on server-rendered documents whose+ inline script body varies per request, so no build-time hash can cover them. Everything else is expected+ to use the hashes in [[inline-js-hashes]]."+ ::script-nonce?)+(defn- generate-nonce- "Generates a random nonce of 10 characters to add to the `Content-Security-Policy` header so that only scripts and- inline style elements with the same nonce will be allowed to run. The server generates a unique nonce value each- time it sends a response. For more information see+ "Generates a random nonce of 10 characters to add to the `Content-Security-Policy` header so that only+ style elements with the same nonce will be allowed to apply. The app document hands this value to page+ JS, which needs it to inject styles at runtime (Emotion, CodeMirror, ECharts). The server generates a+ unique nonce value each time it sends a response. `script-src` only carries the nonce for responses that+ set [[script-nonce-response-key]]. For more information seehttps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src."[](let [chars "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"@@ -238,16 +246,20 @@(defn- content-security-policy-header"`Content-Security-Policy` header. See https://content-security-policy.com for more details."- [nonce data-app-iframe? data-app-connect-hosts allow-blob-img?]+ [nonce script-nonce? data-app-iframe? data-app-connect-hosts allow-blob-img?]{"Content-Security-Policy"(str/join(for [[k vs] {:default-src ["'none'"]:script-src (concat["'self'"- ;; for custom viz plugin bundles loaded via fetch + inline <script> with nonce.+ ;; Only responses that set [[script-nonce-response-key]] get a nonce here.+ ;; The app document deliberately does not: its inline scripts are covered by+ ;; the hashes below, and it hands the nonce to page JS so styles can be+ ;; injected at runtime, which would make a `script-src` nonce reachable by+ ;; anything that can read the page.;; In dev mode 'unsafe-inline' covers this; adding a nonce there would;; cause the browser to ignore 'unsafe-inline' per the CSP spec.- (when (and nonce (not config/is-dev?))+ (when (and nonce script-nonce? (not config/is-dev?))(format "'nonce-%s'" nonce))"https://maps.google.com""https://accounts.google.com"@@ -382,8 +394,9 @@(or (interactive-embedding-origins) "'none'")))(defn- content-security-policy-header-with-frame-ancestors- [frame-ancestors-mode nonce data-app-iframe? data-app-connect-hosts allow-blob-img?]- (cond-> (update (content-security-policy-header nonce data-app-iframe? data-app-connect-hosts allow-blob-img?)+ [frame-ancestors-mode nonce script-nonce? data-app-iframe? data-app-connect-hosts allow-blob-img?]+ (cond-> (update (content-security-policy-header nonce script-nonce? data-app-iframe? data-app-connect-hosts+ allow-blob-img?)"Content-Security-Policy"#(format "%s frame-ancestors %s;" % (frame-ancestors-value frame-ancestors-mode)));; MANDATORY for data apps — do not remove/weaken. Sole barrier (no JS backstop)@@ -509,13 +522,17 @@"Fetch a map of security headers that should be added to a response based on the passed options.`:frame-ancestors` controls clickjacking protection: `:any` (open embedding),`:self` (same-origin only), or `:none` (default — no framing unless interactive- embedding is configured)."- [& {:keys [origin nonce frame-ancestors allow-cache? data-app-iframe? data-app-connect-hosts allow-blob-img?]- :or {frame-ancestors :none, allow-cache? false, data-app-iframe? false, allow-blob-img? false}}]+ embedding is configured). `:script-nonce?` adds the nonce to `script-src`, see+ [[script-nonce-response-key]]."+ [& {:keys [origin nonce script-nonce? frame-ancestors allow-cache? data-app-iframe? data-app-connect-hosts+ allow-blob-img?]+ :or {frame-ancestors :none, allow-cache? false, script-nonce? false, data-app-iframe? false,+ allow-blob-img? false}}](merge(if allow-cache? cache-far-future-headers (cache-prevention-headers))strict-transport-security-header- (content-security-policy-header-with-frame-ancestors frame-ancestors nonce data-app-iframe? data-app-connect-hosts allow-blob-img?)+ (content-security-policy-header-with-frame-ancestors frame-ancestors nonce script-nonce? data-app-iframe?+ data-app-connect-hosts allow-blob-img?)(access-control-headers origin (embedding.settings/embedding-app-origins-sdk));; Tell browsers not to render our site as an iframe (prevent clickjacking)(x-frame-options-header frame-ancestors)@@ -623,6 +640,7 @@(let [headers (security-headers:origin (get (:headers request) "origin"):nonce (:nonce request)+ :script-nonce? (boolean (get response script-nonce-response-key));; The internal data-app iframe is only ever framed by the;; same-origin Metabase app, so restrict it to `'self'` rather;; than the open embedding `*`. Check it before the broaderdiff --git a/src/metabase/server/routes/index.clj b/src/metabase/server/routes/index.cljindex befa7fa4839..2679c5a231c 100644--- a/src/metabase/server/routes/index.clj+++ b/src/metabase/server/routes/index.clj@@ -90,7 +90,7 @@:assetOnErrorJS (load-inline-js "asset_loading_error"):userLocalizationJSON (escape-script (load-localization (when should-load-locale-params? (:locale params)))):siteLocalizationJSON (escape-script (load-localization (system/site-locale)))- :nonceJSON (escape-script (json/encode nonce))+ :nonce (hiccup.util/escape-html nonce):language (hiccup.util/escape-html (or (i18n/user-locale-string) (system/site-locale))):userColorScheme (escape-script (json/encode (users-settings/color-scheme))):favicon (hiccup.util/escape-html (let [custom-favicon (appearance/application-favicon-url)]diff --git a/test/metabase/api/common_test.clj b/test/metabase/api/common_test.cljindex dbfbe23cb80..35e1a9bb8f7 100644--- a/test/metabase/api/common_test.clj+++ b/test/metabase/api/common_test.clj@@ -26,7 +26,7 @@{:status 404:body "Not found.":headers {"Cache-Control" "max-age=0, no-cache, must-revalidate, proxy-revalidate"- "Content-Security-Policy" (str (-> (@#'mw.security/content-security-policy-header nil false nil false) vals first)+ "Content-Security-Policy" (str (-> (@#'mw.security/content-security-policy-header nil false false nil false) vals first)" frame-ancestors 'none';")"Content-Type" "text/plain""Expires" "Tue, 03 Jul 2001 06:00:00 GMT"diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.cljindex edfd734dcb0..8fdfb66397c 100644--- a/test/metabase/server/middleware/security_test.clj+++ b/test/metabase/server/middleware/security_test.clj@@ -10,7 +10,6 @@[metabase.server.settings :as server.settings][metabase.test :as mt][metabase.util :as u]- [metabase.util.json :as json][stencil.core :as stencil]))(defn- header->directive@@ -72,7 +71,7 @@;; on, its value becomes ordinary pages' `frame-ancestors`. It must stay confined to that;; directive: a `;` in the value must not break out and append further CSP directives. The;; worst is `script-src-elem` — the base policy omits it, so an injected one is honored and- ;; overrides the nonce/hash `script-src` allowlist the app relies on to block XSS.+ ;; overrides the hash-based `script-src` allowlist the app relies on to block XSS.(mt/with-premium-features #{:embedding}(let [csp-directive-names(fn [origins]@@ -363,29 +362,46 @@"https://api.example.com"))))))(deftest nonce-test+ (mt/initialize-if-needed! :web-server)(testing "The nonce in the CSP header should match the nonce in the HTML from a index.html request"- (let [nonceJSON (atom nil)- render-file (mt/original-fn #'stencil/render-file)]+ (let [template-nonce (atom nil)+ render-file (mt/original-fn #'stencil/render-file)];; http/get hits a real Jetty server; handler thread doesn't inherit *local-redefs*.(with-redefs [stencil/render-file (fn [path variables]- (reset! nonceJSON (:nonceJSON variables))+ (reset! template-nonce (:nonce variables));; Use index_template.html instead of index.html so the frontend doesn't;; have to be built to run the test. The only difference between them;; should be the script tags for the webpack bundles(assert (= path "frontend_client/index.html"))(render-file "frontend_client/index_template.html" variables))]- (let [response (http/get (str "http://localhost:" (server.instance/server-port)))- nonce (json/decode @nonceJSON)- csp (get-in response [:headers "Content-Security-Policy"])- style-src (->> (str/split csp #"; *")- (filter #(str/starts-with? % "style-src "))- first)]+ (let [response (http/get (str "http://localhost:" (server.instance/server-port)))+ nonce @template-nonce+ csp (get-in response [:headers "Content-Security-Policy"])+ style-src (header->directive csp "style-src")+ script-src (header->directive csp "script-src")](testing "The nonce is 10 characters long and alphanumeric"(is (re-matches #"^[a-zA-Z0-9]{10}$" nonce)))(testing "The same nonce is in the CSP header"(is (str/includes? style-src (str "nonce-" nonce))))- (testing "The same nonce is in the body of the rendered page"- (is (str/includes? (:body response) nonce))))))))+ (testing "The app document does not get a script-src nonce"+ (is (not (str/includes? script-src "'nonce-"))))+ (testing "The nonce reaches the page only as a script attribute, which the browser then blanks"+ (is (str/includes? (:body response) (format "nonce=\"%s\"" nonce)))+ (is (not (str/includes? (:body response) "_metabaseNonce")))+ (is (= 1 (count (re-seq (re-pattern nonce) (:body response))))+ "the nonce appears exactly once, on the bootstrap script tag")))))))++(deftest script-src-nonce-opt-in-test+ (testing "script-src only carries a nonce for responses that opt in"+ (with-redefs [config/is-dev? false]+ (let [script-src-for (fn [response-extras]+ (-> ((mw.security/add-security-headers+ (fn [_request respond _raise]+ (respond (merge {:status 200 :headers {} :body "ok"} response-extras))))+ {:uri "/" :headers {}} identity identity)+ (csp-directive-from-response "script-src")))]+ (is (not (str/includes? (script-src-for {}) "'nonce-")))+ (is (str/includes? (script-src-for {mw.security/script-nonce-response-key true}) "'nonce-"))))))(deftest data-app-inline-style-csp-test(testing "Only data-app iframe responses allow inline styles"@@ -408,7 +424,7 @@(is (not (str/includes? app-style-src "'unsafe-inline'")))(is (str/includes? data-style-src "'unsafe-inline'"))(is (not (str/includes? data-style-src "'nonce-")))- (is (str/includes? data-script-src "'nonce-"))+ (is (not (str/includes? data-script-src "'nonce-")))(is (not (str/includes? data-script-src "'unsafe-inline'")))))));; NOTE: `unsafe-eval` was removed from the data-app iframe document (it now lives