3

I am on rails 4.2.1 (ruby 2.2.1p85) and I want to sanitize user input and also have that text cleared out of the post/get params. I don't want to solely depend on native rails 4 auto escaping.

Being a bit new to rails I was not aware of the sanitize options. http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

I was originally going to create a helper for such purposes so I could do something as shown below. I'm trying to sanitize form input to secure against Cross-site scripting (XSS) vulnerabilities.

basic helper example This works but its probably not the best rails way to do it? Also the text is still in the post/get request.

<%= text_field_tag :input_text, Safetxt(params[:input_text])  %>

helper method

  def Safetxt(input_value)
    txtOut = input_value
    if txtOut.blank?
      txtOut = ""
    else
      txtOut = txtOut.gsub("<script>", "")
      txtOut = txtOut.gsub("</script>", "")
    end
    return txtOut
  end

on submit the input_text is cleaned on output but the get/post values still contain the stripped values.

input_text=<script>alert%28"blah"%29<%2Fscript>

How can I utilize a custom scrubber in a helper method to properly sanitize input (remove dangerous text,tags)? I'm a bit confused how to implement this properly with custom rules.

For example something as shown below (I know this is wrong). Also what is the best way to exclude that text in the post/get request as well? I know I should sanitize the text in the controller side for input, but if there is a way, I'd like that text to be cleared on the submit request if that's possible.

def Safetxt(input_value)
    scrubber = Rails::Html::TargetScrubber.new
    scrubber.tags = ['script']
    txtOut = input_value
    if txtOut.blank?
      txtOut = ""
    else
      txtOut.scrub!(scrubber)
    end
    return txtOut
  end  

1 Answer 1

0

You can use the Rails 4 sanitize method to strip out tags that are not "whitelisted" by default by rails.

So in your controller code you can have:

ActionView::Base.new.sanitize("<script>alert('hello')</script>")

which would strip out the script tag. You can whitelist your own attributes or elements rather than the default or if you want more custom behavior you can define your own scrubber in the sanitize method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.