Skip to content

Commit

Permalink
Limit recursion in regex parser (#757)
Browse files Browse the repository at this point in the history
Cherry-picks some more changes from swift/main.

* Limit recursion in regex parser

* Also check for custom char class nesting
  • Loading branch information
milseman committed Sep 11, 2024
1 parent c75631d commit 2ac5bb5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Sources/_RegexParser/Regex/Parse/Parse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,19 @@ extension Parser {
mutating func parseCustomCharacterClass(
_ start: Source.Located<CustomCC.Start>
) -> CustomCC {
// Excessively nested recursion is a common DOS attack, so limit
// our recursion.
context.parseDepth += 1
defer { context.parseDepth -= 1 }
guard context.parseDepth < context.maxParseDepth else {
self.errorAtCurrentPosition(.nestingTooDeep)

// This is not generally recoverable and further errors will be
// incorrect
diags.suppressFurtherDiagnostics = true
return .init(start, [], start.location)
}

let alreadyInCCC = context.isInCustomCharacterClass
context.isInCustomCharacterClass = true
defer { context.isInCustomCharacterClass = alreadyInCCC }
Expand Down
7 changes: 7 additions & 0 deletions Tests/RegexTests/ParseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3335,6 +3335,13 @@ extension RegexTests {
+ "a"
+ String(repeating: ")*", count: 500),
.nestingTooDeep)

diagnosticTest(
String(repeating: "[", count: 500)
+ "a"
+ String(repeating: "]*", count: 500),
.nestingTooDeep)

}

func testDelimiterLexingErrors() {
Expand Down

0 comments on commit 2ac5bb5

Please sign in to comment.