Skip to content

Commit

Permalink
Regular expression fix
Browse files Browse the repository at this point in the history
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
Dan Croak committed Mar 26, 2013
1 parent 7723370 commit 01db6c5
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/email_validator.rb
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions spec/email_validator_spec.rb
Expand Up @@ -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
Expand Down Expand Up @@ -163,4 +164,4 @@ class TestUserWithMessage < TestModel
end
end
end
end
end

0 comments on commit 01db6c5

Please sign in to comment.