Permalink
Browse files

Regular expression fix

In Ruby, `^` and `$` match the line beginning and line end. So, an email
coming in via HTTP like this:

    user@example.com%0A<script>alert('hello')</script>

Whereas %0A is a line feed in URL encoding, so Rails automatically
converts it to:

    user@example.com\n<script>alert('hello')</script>

and unintentionally passes validation because the regular expression
matched the email: up to the line end, the rest does not matter.

http://guides.rubyonrails.org/security.html#regular-expressions
  • Loading branch information...
1 parent 7723370 commit 01db6c53cbe58174420833552e5009ff536dac16 @croaky croaky committed Mar 26, 2013
Showing with 4 additions and 3 deletions.
  1. +1 −1 lib/email_validator.rb
  2. +3 −2 spec/email_validator_spec.rb
View
@@ -9,7 +9,7 @@ def self.default_options
def validate_each(record, attribute, value)
options = @@default_options.merge(self.options)
name_validation = options[:strict_mode] ? "-a-z0-9+._" : "^@\\s"
- unless value =~ /^\s*([#{name_validation}]{1,64})@((?:[-a-z0-9]+\.)+[a-z]{2,})\s*$/i
+ unless value =~ /\A\s*([#{name_validation}]{1,64})@((?:[-a-z0-9]+\.)+[a-z]{2,})\s*\z/i
record.errors.add(attribute, options[:message] || :invalid)
end
end
@@ -84,7 +84,8 @@ class TestUserWithMessage < TestModel
"invalid-ip@127.0.0.1.26",
"another-invalid-ip@127.0.0.256",
"IP-and-port@127.0.0.1:25",
- "the-local-part-is-invalid-if-it-is-longer-than-sixty-four-characters@sld.net"
+ "the-local-part-is-invalid-if-it-is-longer-than-sixty-four-characters@sld.net",
+ "user@example.com\n<script>alert('hello')</script>"
].each do |email|
it "#{email.inspect} should not be valid" do
@@ -163,4 +164,4 @@ class TestUserWithMessage < TestModel
end
end
end
-end
+end

0 comments on commit 01db6c5

Please sign in to comment.