From: =?utf-8?q?Bastien_Roucari=C3=A8s?= <rouca@debian.org>
Date: Wed, 1 Mar 2023 10:10:47 +0000
Subject: Partial fix of ReDos CVE-2022-21222/CVE-2021-33587: trim string
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

Trim left the string avoiding a \s* at the beginning of the string, thus avoiding part of complexity.

bug-debian: https://bugs.debian.org/989264
bug-debian: https://bugs.debian.org/1032188
bug: https://www.cve.org/CVERecord?id=CVE-2022-21222
bug: https://www.cve.org/CVERecord?id=CVE-2021-33587
Signed-off-by: Bastien Roucariès <rouca@debian.org>
---
 src/parse.ts | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/src/parse.ts b/src/parse.ts
index 628561b..ad11230 100644
--- a/src/parse.ts
+++ b/src/parse.ts
@@ -81,7 +81,7 @@ export type TraversalType =
 const reName = /^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/;
 const reEscape = /\\([\da-f]{1,6}\s?|(\s)|.)/gi;
 // Modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87
-const reAttr = /^\s*(?:(\*|[-\w]*)\|)?((?:\\.|[\w\u00b0-\uFFFF-])+)\s*(?:([~|^$*!]?)=\s*(?:(['"])((?:[^\\]|\\[^])*?)\4|(#?(?:\\.|[\w\u00b0-\uFFFF-])*)|)|)\s*([iI])?\]/;
+const reAttr = /^(?:(\*|[-\w]*)\|)?((?:\\.|[\w\u00b0-\uFFFF-])+)\s*(?:([~|^$*!]?)=\s*(?:(['"])((?:[^\\]|\\[^])*?)\4|(#?(?:\\.|[\w\u00b0-\uFFFF-])*)|)|)\s*([iI])?\]/;
 
 const actionTypes: { [key: string]: AttributeAction } = {
     undefined: "exists",
@@ -263,8 +263,13 @@ function parseSelector(
                     namespace: null,
                 });
             } else if (firstChar === "[") {
+		const wmatch = selector
+		      .slice(selectorIndex + 1)
+		      .match(/^\s*/);
+		const woffset = !wmatch ? 0 : wmatch[0].length;
+
                 const attributeMatch = selector
-                    .slice(selectorIndex + 1)
+                    .slice(selectorIndex + 1 + woffset)
                     .match(reAttr);
 
                 if (!attributeMatch) {
@@ -286,7 +291,7 @@ function parseSelector(
                     ignoreCase,
                 ] = attributeMatch;
 
-                selectorIndex += completeSelector.length + 1;
+                selectorIndex += completeSelector.length + 1 + woffset;
                 let name = unescapeCSS(baseName);
 
                 if (options.lowerCaseAttributeNames ?? !options.xmlMode) {
