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
Ensure CSV strings show as strings in excel (#81258)
Nathan Voxland85f1e975a5c9
diff --git a/src/metabase/query_processor/streaming/common.clj b/src/metabase/query_processor/streaming/common.cljindex 8125e8d0ba1..482844ca4d7 100644--- a/src/metabase/query_processor/streaming/common.clj+++ b/src/metabase/query_processor/streaming/common.clj@@ -38,6 +38,38 @@#_{:clj-kondo/ignore [:deprecated-var]}(qp.store/cached ::results-timezone (t/zone-id (qp.timezone/results-timezone-id)))))+(def ^:private formula-trigger-chars+ "Leading characters that make Excel/Google Sheets/LibreOffice parse an imported cell as a formula rather than as+ text. Tab and carriage return are included because spreadsheet apps strip them, promoting the next character to the+ front."+ #{\= \+ \- \@ \tab \return})++(def ^:private plain-number-re+ "Matches values a spreadsheet reads as an ordinary number, so a leading `-`/`+` on them is harmless (`-1,234.56` is+ the number, not a formula). Deliberately conservative: only digits, group/decimal separators, whitespace, currency+ symbols, an exponent and a trailing `%`. Nothing that matches this can carry formula syntax, so exempting it can't+ reopen the injection."+ #"[-+]?\p{Sc}?\s?\d[\d,\s.]*(?:[eE][-+]?\d+)?\s?\p{Sc}?\s?%?")++(defn escape-spreadsheet-formula+ "Neutralize spreadsheet formula (a.k.a. CSV/DDE) injection in an exported cell value: a value an attacker planted in+ a queried table -- e.g. `=cmd|' /C calc'!A0` -- would otherwise be evaluated when the export is opened in Excel or+ Sheets. Prefixes a single quote so the leading character is no longer a formula trigger.++ This applies to *text* export formats only. XLSX does not need it: POI writes cell values as string-typed cells+ (`t=\"inlineStr\"`, no `<f>` element), which Excel renders literally, and the prefix would be a real character in the+ cell rather than a text marker -- visible junk for no security gain.++ Only strings are candidates; everything else (numbers, booleans, temporal values) is written as a typed value and+ passes through untouched. Values that are plainly numeric are left alone so exports stay faithful. See SEC-763."+ [v]+ (if (and (string? v)+ (pos? (count v))+ (contains? formula-trigger-chars (nth v 0))+ (not (re-matches plain-number-re v)))+ (str "'" v)+ v))+(defprotocol FormatValue"Protocol for specifying how objects of various classes in QP result rows should be formatted in various downloadresults formats (e.g. CSV, as opposed to the 'normal' API response format, which doesn't use this logic)."diff --git a/src/metabase/query_processor/streaming/csv.clj b/src/metabase/query_processor/streaming/csv.cljindex a817e72cd69..6372637609c 100644--- a/src/metabase/query_processor/streaming/csv.clj+++ b/src/metabase/query_processor/streaming/csv.clj@@ -28,6 +28,13 @@(streaming.common/export-filename-timestamp))}:write-keepalive-newlines? false}))+(defn- escape-cell+ "Stringify a cell the way [[clojure.data.csv/write-cell]] would, then neutralize spreadsheet formula injection. The+ `str` matters: a formatter may hand us a wrapper record (e.g. `TextWrapper`) whose `toString` is what actually gets+ written, so checking the raw value would miss it."+ [cell]+ (streaming.common/escape-spreadsheet-formula (str cell)))+(defn- write-csv"Custom implementation of `clojure.data.csv/write-csv` with a more efficient quote? predicate and configurableseparator."@@ -47,7 +54,11 @@true(recur (unchecked-inc i))))))))newline "\n"]- (#'clojure.data.csv/write-csv* writer data separator quote quote? newline)))+ ;; Escaping here rather than at each call site covers header rows, plain rows and pivot output in one place. It+ ;; deliberately does *not* go in the `write-cell` rebind below: that is a global root binding, and formula escaping+ ;; must not reach the other `data.csv` writers -- the content-translation dictionary is exported, edited and+ ;; re-uploaded, and `setting/serialize-csv` writes to the app DB.+ (#'clojure.data.csv/write-csv* writer (map #(mapv escape-cell %) data) separator quote quote? newline)));; Rebind write-cell to avoid using clojure.core/escape. Instead, use String.replace with known arguments (we never;; change quote symbol anyway).diff --git a/test/metabase/query_processor/streaming/common_test.clj b/test/metabase/query_processor/streaming/common_test.cljindex b3bc8b43d16..a33cc37637e 100644--- a/test/metabase/query_processor/streaming/common_test.clj+++ b/test/metabase/query_processor/streaming/common_test.clj@@ -98,3 +98,39 @@::mb.viz/link-type ::mb.viz/url::mb.viz/link-text-template "http://example.com"}(::mb.viz/click-behavior settings)))))))++(deftest escape-spreadsheet-formula-test+ (testing "values that a spreadsheet would evaluate as a formula are prefixed with a single quote"+ (are [v] (= (str "'" v) (streaming.common/escape-spreadsheet-formula v))+ "=1+1"+ "=cmd|' /C calc'!A0"+ "+cmd|' /C calc'!A0"+ "-cmd|' /C calc'!A0"+ "@SUM(1+1)"+ "=HYPERLINK(\"http://evil.example\",\"click me\")"+ "-2+3"+ "\t=1+1"+ "\r=1+1"))+ (testing "ordinary values are left alone"+ (are [v] (= v (streaming.common/escape-spreadsheet-formula v))+ nil+ ""+ "hello"+ "a=b"+ "Sale: 50% off"+ " =1+1"))+ (testing "values a spreadsheet reads as plain numbers are left alone, so exports stay faithful"+ (are [v] (= v (streaming.common/escape-spreadsheet-formula v))+ "-5"+ "+5"+ "-1,234.56"+ "-$1,234.56"+ "-50%"+ "-1.5e3"+ "+1 555 1234"))+ (testing "non-string values pass through untouched"+ (are [v] (= v (streaming.common/escape-spreadsheet-formula v))+ 5+ -5+ true+ :kw)))diff --git a/test/metabase/query_processor/streaming/csv_test.clj b/test/metabase/query_processor/streaming/csv_test.cljindex 3925572a731..faecc713070 100644--- a/test/metabase/query_processor/streaming/csv_test.clj+++ b/test/metabase/query_processor/streaming/csv_test.clj@@ -114,23 +114,30 @@["5" "118.26100000° W" "34.07780000° N"]](parse-and-sort-csv result))))))-(defn- csv-export- "Given a seq of result rows, write it as a CSV, then read the CSV and return the resulting data."- [rows]+(defn- csv-export-with-cols+ "Given `ordered-cols` and a seq of result rows, write it as a CSV, then read the CSV back. Includes the header row."+ [ordered-cols rows](driver/with-driver :h2(mt/with-metadata-provider (mt/id)(with-open [bos (ByteArrayOutputStream.)os (BufferedOutputStream. bos)](let [results-writer (qp.si/streaming-results-writer :csv os)]- (qp.si/begin! results-writer {:data {:ordered-cols [{:base_type :type/*}- {:base_type :type/*}- {:base_type :type/*}]}} {})+ (qp.si/begin! results-writer {:data {:ordered-cols ordered-cols}} {})(doall (map-indexed(fn [i row] (qp.si/write-row! results-writer row i [] {}))rows))(qp.si/finish! results-writer {:row_count (count rows)}))(let [bytea (.toByteArray bos)]- (rest (csv/read-csv (String. bytea))))))))+ (->> (csv/read-csv (u/strip-bom (String. bytea)))+ (map vec)))))))++(defn- csv-export+ "Given a seq of result rows, write it as a CSV, then read the CSV and return the resulting data."+ [rows]+ (rest (csv-export-with-cols [{:base_type :type/*}+ {:base_type :type/*}+ {:base_type :type/*}]+ rows)))(deftest csv-export-includes-utf8-bom-test(testing "CSV exports start with a UTF-8 BOM so Excel renders non-ASCII chars like £ correctly"@@ -247,3 +254,14 @@(is (= 2 (count lines)) "Should have header and one data row")(is (str/includes? (second lines) "\"")"Value containing separator should be quoted")))))++(deftest formula-injection-test+ (testing "cell values that a spreadsheet would evaluate as a formula are neutralized (SEC-763)"+ (is (= [["'=1+1" "'@SUM(1+1)" "'+cmd|' /C calc'!A0"]+ ["'-cmd|' /C calc'!A0" "not a formula" "-1,234.56"]]+ (csv-export [["=1+1" "@SUM(1+1)" "+cmd|' /C calc'!A0"]+ ["-cmd|' /C calc'!A0" "not a formula" "-1,234.56"]]))))+ (testing "column titles are neutralized too, since they can come from attacker-controlled table metadata"+ (let [result (csv-export-with-cols [{:name "=1+1" :display_name "=1+1" :base_type :type/Text}]+ [["ok"]])]+ (is (= ["'=1+1"] (first result))))))