Output the following strings including Script tags in various ways and compare the differences.
@hoge
<script>
alert('you are an idiot');
</script>
erb
<%= @hoge %>
output
<script> alert('you are an idiot'); </script>
XSS can be avoided, but line breaks and spaces are not reflected
html_safe
erb
<%= @hoge.html_safe %>
output
Script is executed!
Induces XSS. Despite its name, html_safe
is not safe at all.
simple_format(@hoge
, sanitize: true)
erb
<%= simple_format(@hoge, sanitize: true) %>
output
alert('you are an idiot');
The script
tag is erased
h(@hoge
)
erb
<%= h(@hoge) %>
output
<script> alert('you are an idiot'); </script>
XSS can be avoided, but line breaks and spaces are not reflected
simple_format(h(@hoge
))
erb
<%= simple_format(h(@hoge)) %>
output
<script>
alert('you are an idiot');
</script>
XSS does not occur. The script tag is escaped and the line breaks are retained. Only the space after the line break is not reflected.
If you want to reflect line breaks, simple_format (h (@hoge)
seems to be good.
Recommended Posts