Created
August 3, 2011 02:10
-
-
Save bradleybeddoes/1121736 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Regular expressions | |
| A common pitfall in Ruby's regular expressions is to match the string's be- | |
| ginning and end by ^ and $, instead of \A and \z. | |
| Ruby uses a slightly different approach to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular ex- pression like this: | |
| class File < ActiveRecord::Base | |
| validates_format_of :name, :with => /^[\w\.\-\+]+$/ | |
| end | |
| This means, upon saving, the model will validate the file name to consist only of alpha- numeric characters, dots, + and -. And the programmer added ^ and $ so that file name will contain these characters from the beginning to the end of the string. However, in Ruby ^ and $ matches theline beginning and end. And thus a file name like this passes the filter without problems: | |
| file.txt%0A<script>alert('hello')</script> | |
| Whereas %0A is a line break in URL encoding, so Rails automatically converts it to "file.txt\n<script>alert('hello')</script>". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read: | |
| /\A[\w\.\-\+]+\z/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment