regex-dos
Input matched against a pattern that can take exponential or quadratic time.
- Group
- Code
- Runs
- Runs under ur scan:
ur scan --rule regex-dos - Level
- warning
- Reads
- Every file
- Fix
- None: the safe form depends on what the value is meant to be
Why
A value from a request is matched against a regular expression that a backtracking matcher, as Ruby's before 3.2, can take minutes to fail on. One that repeats a group that repeats, as (a+)+ does, makes it try every way of splitting a short input that almost matches; one whose start nothing anchors and repeats without bound, as \d+- does, makes it run the repetition to the end of a long input again from every offset. Rewrite the pattern so no repetition nests, anchor it with \A, bound its repetitions, or limit the input's length first.
The fix, as Ur suggests it: anchor the pattern, or remove the nested repetition.
For agents
Never match input against a pattern with a repeated group that repeats, or an unanchored start that repeats without bound.
Example
app/controllers/signups_controller.rbclass SignupsController < ApplicationController
def check
username = params[:username]
valid = username =~ /^(a+)+$/
render json: { valid: valid }
end
end
$ ur scan --rule regex-dos
warning[regex-dos]: `params`, a request parameter, reaches `=~`
--> ./app/controllers/signups_controller.rb:4:13 method `check`
= step 1: ./app/controllers/signups_controller.rb:3:16 `params`, a request parameter,
= hint: anchor the pattern, or remove the nested repetition
= see: CWE-1333: Inefficient Regular Expression Complexity, MITRE (2024-11-19), https://cwe.mitre.org/data/definitions/1333.html
scanned 1 file (no framework recognized)
regex-dos: 1 high, 0 medium
1 finding and 0 of medium confidence
Example
app/controllers/password_resets_controller.rbclass PasswordResetsController < ApplicationController
def edit
if params[:token] =~ /(?<user>\d+)-(?<digest>[A-Z0-9]{32})/i
@user = User.find_by(id: $~[:user])
end
end
end
$ ur scan --rule regex-dos
warning[regex-dos]: `params`, a request parameter, reaches `=~`, whose pattern takes quadratic time: it runs `\d+` from every offset
--> ./app/controllers/password_resets_controller.rb:3:8 method `edit`
= step 1: ./app/controllers/password_resets_controller.rb:3:8 `params`, a request parameter,
= hint: anchor the pattern, or remove the nested repetition
= see: CWE-1333: Inefficient Regular Expression Complexity, MITRE (2024-11-19), https://cwe.mitre.org/data/definitions/1333.html
scanned 1 file (no framework recognized)
regex-dos: 1 high, 0 medium
1 finding and 0 of medium confidence
Source
CWE-1333: Inefficient Regular Expression Complexity, MITRE (2024-11-19).