Tuesday, July 31, 2007

sanitizing Rails input parameters

I really like how Tapestry automagically escapes HTML input when posted from a form. In fact, it was just great never having to worry about that when coding. I'd like to have the same functionality in Rails especially after reading about Rails XSS vulnerabilities and work-arounds. Since the webapp I'm writing has no requirements for allowing formatted user input, I just need something simple to clean/sanitize all the params. Here's the latest:

#escapes all HTML from the given hash's values (recursively applied as needed)
def sanitize(hash)
dirty_hash = hash

dirty_hash.keys.each do |key|
value = dirty_hash[key]

dirty_hash[key] = sanitize(value)
if (value && value.kind_of?(String))
dirty_hash[key] = CGI.escapeHTML(value)

hash = dirty_hash

This is then invoked by a before_filter. Seems to do the job, is there a better/cleaner/faster way of doing this? Let me know how it could be improved...

No comments: