Reputation: 127
In my rails application_helper.rb file, there is a parse method. Inside that method is a string variable html, which contains
<form>
, other html tags, and
in its value. I will call parse inside my view index.html.erb, with
<%= parse() %>
The call to parse will output the value of the html variable.
Quite unexpectedly, I noticed that the view renders a webpage which the browser didn't process at all, i.e., the webpage contains the writing
<form>
instead of rendering a form; and so on for all the other tags, such as
<br>.
And
was also not replaced by a corresponding space.
On checking the source code of the webpage, I noticed that all the ampersands(such as of
) was sent by the view to the browser as
&
and < was sent as
<
and similiarly for >.
So, what did happen? Putting
<parse()>
inside
<%= %>
processed the value of html before handing it out to the browser? Why?
Another piece of the puzzle is, the webpage was rendered fine when I put parse() inside
<%== %>
(I know
<%== %>
is not a correct syntax, I just discovered this piece of puzzle about it by mistake.)
So what is going on?
Upvotes: 1
Views: 32
Reputation: 1784
<%= =>
Escapes all tags for security reasons. For instance I will put some script into my name: <script>...something bad to steal your accesses, cookies, make redirects, etc</script>
. When you visit my profile, this script will be executed. This attack is called Cross Site Scripting (XSS). So rails cares about you and escape all such thing to prevent XSS attacks.
What you are looking for is to call your expression this way:
<%= raw(parse()) %>
OR it's alias, that you mentioned:
<%== parse() %>
More details -- http://edgeguides.rubyonrails.org/active_support_core_extensions.html#output-safety
This should keep all your tags without escaping.... but keep in mind... if you have any kind of data, that was input by the user in parse
, then you will open an XSS vulnerability in your application. It's not something you should NEVER do. It's something that you should do only in case, when you know what you are doing ;)
Upvotes: 2