We conducted a security diagnosis of the application currently under development, but found a vulnerability called XSS (Cross-Site Scripting) and decided to address it. It seems to be too obvious knowledge for a web developer, but it was the first time for me to deal with it, so it was quite difficult. I've had some stumbling blocks, so I'll write one of them this time.
https://qiita.com/kamohicokamo/items/571c58f2d6738a7dfe6a With reference to this article, I would like to sanitize the data for XSS countermeasures.
haml:name.html.haml
'Yamada Taro<script>alert("Yamada Taroです")</script>'
If you display it as it is,
The embedded JavaScript is executed. This is bad for security.
= sanitize 'Yamada Taro<script>alert("Yamada Taroです")</script>'
With this sanitize
,
In this way the script tag is removed and it becomes just text.
You may bother to write sanitize
in View, but I want to disable it when a character string containing html tags is input.
However, since this sanitize
method is a helper method, it is difficult to use except for View ...
I made a method like this.
model
def remove_script_tag(str)
ActionController::Base.helpers.sanitize(str)
end
sanitize
method removes only the<script>
tag by default, so it is set as remove_script_tag
.If you use this method well with before_validation
or before_save
, you should be able to invalidate even if a malicious script is sent as a string.
ruby 2.6.6 rails 6.0.3.2
Recommended Posts