Rules / Ruby
SHIELD-RUBY-023
Regex denial of service via interpolated pattern
What it detects
Building a Regexp from unsanitized user input can create catastrophic backtracking patterns.
How to fix
Escape user input with Regexp.escape or match against a fixed anchored pattern.
Vulnerable — Shield flags thisapp/controllers/products_controller.rb
class ProductsController < ApplicationController
def search
pattern = Regexp.new(params[:q])
@products = Product.all.select { |p| p.name =~ pattern }
end
end
Fixed — scans cleanapp/controllers/products_controller.rb
class ProductsController < ApplicationController
def search
pattern = Regexp.new(Regexp.escape(params[:q].to_s))
@products = Product.all.select { |p| p.name =~ pattern }
end
end
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-RUBY-023, the fixed one does not.