From 90ae3c1f760bd14609a4480f3a56b373f7b1353a Mon Sep 17 00:00:00 2001 From: Tilman Vatteroth Date: Tue, 31 Aug 2021 22:23:18 +0200 Subject: [PATCH] Fix DoS in CSV parser (#1467) * Fix DoS in CSV parser Signed-off-by: Tilman Vatteroth --- .../replace-components/csv/csv-parser.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/components/markdown-renderer/replace-components/csv/csv-parser.ts b/src/components/markdown-renderer/replace-components/csv/csv-parser.ts index d956262a9..87b912311 100644 --- a/src/components/markdown-renderer/replace-components/csv/csv-parser.ts +++ b/src/components/markdown-renderer/replace-components/csv/csv-parser.ts @@ -4,11 +4,27 @@ * SPDX-License-Identifier: AGPL-3.0-only */ +/** + * Parses a given text as comma separated values (CSV). + * + * @param csvText The raw csv text + * @param csvColumnDelimiter The delimiter for the columns + * @return the values splitted by rows and columns + */ export const parseCsv = (csvText: string, csvColumnDelimiter: string): string[][] => { const rows = csvText.split('\n') if (!rows || rows.length === 0) { return [] } - const splitRegex = new RegExp(`${csvColumnDelimiter}(?=(?:[^"]*"[^"]*")*[^"]*$)`) + const splitRegex = new RegExp(`${escapeRegexCharacters(csvColumnDelimiter)}(?=(?:[^"]*"[^"]*")*[^"]*$)`) return rows.filter((row) => row !== '').map((row) => row.split(splitRegex)) } + +/** + * Escapes regex characters in the given string so it can be used as literal string in another regex. + * @param unsafe The unescaped string + * @return The escaped string + */ +const escapeRegexCharacters = (unsafe: string): string => { + return unsafe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +}