How to use html_safe in a secure manner?

981 Views Asked by At

I was wondering when it is safe to use html_safe and when not. I read that you don't want to do this if the code may contain user content. What does this mean in practice?

flash[:danger]="Dear #{@user.username} <br> please take a look #{view_context.link_to('here', some_path)}" <br> Your organization #{@user.organizationname} bla bla"

For example, for a flash message such as this one, will need html_safe to display correctly, but it also contains in this case username and organizationname which is content entered by the user. Is it then still safe to use html_safe...?

2

There are 2 best solutions below

2
Axel Tetzlaff On BEST ANSWER

If you inject user content into strings you render with html_safe you have to make sure all the injected content is sanitized

flash[:danger]="Dear #{ActionController::Base.helpers.sanitize @user.username} <br> please take a look #{view_context.link_to('here', some_path)}" <br> Your organization #{ActionController::Base.helpers.sanitize @user.organizationname} bla bla"

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

0
Borsunho On

Generally speaking, it is not, malevolent user could enter some harmful js code as his organizationname, and this code would than become part of your app - you don't want this. This attack is known as Cross-site scripting (XSS), and you can read about it i.e. here: http://www.jasonwieringa.com/Learning-About-XSS-Attacks-in-Rails/

As axel pointed, you should call sanitize on every user input that you want to mark as html_safe what it does is replacing all html special characters as entities, so any unwanted markup or js code will not be interpreted by user browser.