Skip to content

Commit

Permalink
Prevent catastrophic backtracking during mime parsing
Browse files Browse the repository at this point in the history
The regular expression used to parse the mime type can results in
catastrophic backtracking[1] allowing for a ReDOS attack[2].

This commit uses atomic grouping[3] to prevent backtracking.

1. https://www.regular-expressions.info/catastrophic.html
2. https://en.wikipedia.org/wiki/ReDoS
3. https://www.regular-expressions.info/atomic.html

[CVE-2021-22902]
  • Loading branch information
security-curious authored and tenderlove committed May 4, 2021
1 parent 0073c7b commit 446afbd
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion actionpack/lib/action_dispatch/http/mime_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def unregister(symbol)
MIME_PARAMETER_KEY = "[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}"
MIME_PARAMETER_VALUE = "#{Regexp.escape('"')}?[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}#{Regexp.escape('"')}?"
MIME_PARAMETER = "\s*\;\s*#{MIME_PARAMETER_KEY}(?:\=#{MIME_PARAMETER_VALUE})?"
MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME})(?:\s*#{MIME_PARAMETER}\s*)*)\z/
MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME})(?>\s*#{MIME_PARAMETER}\s*)*)\z/

class InvalidMimeType < StandardError; end

Expand Down
6 changes: 6 additions & 0 deletions actionpack/test/dispatch/mime_type_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -225,5 +225,11 @@ class MimeTypeTest < ActiveSupport::TestCase
assert_raises Mime::Type::InvalidMimeType do
Mime::Type.new(nil)
end

assert_raises Mime::Type::InvalidMimeType do
Timeout.timeout(1) do # Shouldn't take more than 1s
Mime::Type.new("text/html ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0 ;0;")
end
end
end
end

0 comments on commit 446afbd

Please sign in to comment.