Skip to content

Commit 71c9314

Browse files
authored
fix: mitigate ReDoS when generating examples from pattern (#10477)
1 parent c2cda8e commit 71c9314

File tree

2 files changed

+25
-3
lines changed
  • src/core/plugins

2 files changed

+25
-3
lines changed

src/core/plugins/json-schema-2020-12-samples/fn/core/random.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,18 @@ export const bytes = (length) => randomBytes(length)
1616

1717
export const randexp = (pattern) => {
1818
try {
19-
const randexpInstance = new RandExp(pattern)
19+
/**
20+
* Applying maximum value (100) to numbers from regex patterns to avoid ReDoS:
21+
* 1. {x}
22+
* 2. {x,}
23+
* 3. {,y}
24+
* 4. {x,y}
25+
*/
26+
const patternSanitizer =
27+
/(?<=(?<!\\)\{)(\d{3,})(?=\})|(?<=(?<!\\)\{\d*,)(\d{3,})(?=\})|(?<=(?<!\\)\{)(\d{3,})(?=,\d*\})/g
28+
const safePattern = pattern.replace(patternSanitizer, "100")
29+
const randexpInstance = new RandExp(safePattern)
30+
randexpInstance.max = 100
2031
return randexpInstance.gen()
2132
} catch {
2233
// invalid regex should not cause a crash (regex syntax varies across languages)

src/core/plugins/json-schema-5-samples/fn/index.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,19 @@ import memoizeN from "core/utils/memoizeN"
66

77
const generateStringFromRegex = (pattern) => {
88
try {
9-
const randexp = new RandExp(pattern)
10-
return randexp.gen()
9+
/**
10+
* Applying maximum value (100) to numbers from regex patterns to avoid ReDoS:
11+
* 1. {x}
12+
* 2. {x,}
13+
* 3. {,y}
14+
* 4. {x,y}
15+
*/
16+
const patternSanitizer =
17+
/(?<=(?<!\\)\{)(\d{3,})(?=\})|(?<=(?<!\\)\{\d*,)(\d{3,})(?=\})|(?<=(?<!\\)\{)(\d{3,})(?=,\d*\})/g
18+
const safePattern = pattern.replace(patternSanitizer, "100")
19+
const randexpInstance = new RandExp(safePattern)
20+
randexpInstance.max = 100
21+
return randexpInstance.gen()
1122
} catch (e) {
1223
// Invalid regex should not cause a crash (regex syntax varies across languages)
1324
return "string"

0 commit comments

Comments
 (0)