Monday 14 July 2008

Combating XSS

This info is available elsewhere, but as I always forget, this is a good place to repeat it.

Install the White List plugin. Get it here

Once installed you'll need to add the following line to the init.rb of the white_list plugin:
ActionView::Base.send :include, WhiteListHelper


In the Application.rb (Application Controller)
include HtmlFilterHelper
before_filter :sanitize_params


Then I have a class called HtmlFilterHelper
module HtmlFilterHelper
def sanitize_params(params = params)
params = walk_hash(params) if params
end

private
def walk_hash(hash)
hash.keys.each do |key|
if hash[key].is_a? String
hash[key] = white_list(hash[key])
elsif hash[key].is_a? Hash
hash[key] = walk_hash(hash[key])
elsif hash[key].is_a? Array
hash[key] = walk_array(hash[key])
end
end
hash
end

def walk_array(array)
array.each_with_index do |el,i|
if el.is_a? String
array[i] = white_list(el)
elsif el.is_a? Hash
array[i] = walk_hash(el)
elsif el.is_a? Array
array[i] = walk_array(el)
end
end
array
end
end


For what it is worth, I also do stuff like this:

<%=white_list synopsis.synopsis[0,100].gsub(/<\/?[^>]*>/, "")%>


Which removes any html-style tags from the text and then white_list's it before outputting.

No comments: