Cross-site Scripting is a common security issue during development. This occurs when users are allowed to directly input HTML and JavaScript scripts. In the following website, we did not filter the input content, leading to some security vulnerabilities.
If you enter the content surrounded by <SCRIPT> in the input box, when the page is loaded, the script is executed and displayed at the front end each time. For example, if you enter <SCRIPT> alert ('hello') </SCRIPT> and save it, the alert window is displayed every time you browse this page.
The Javascript script for embedding the page is as follows: Terminal
Cross-site Scripting may be used for malicious attacks. For example, you can read the cookies of other users on the site. Sending users' cookies to remote servers is as easy as alert content. Session IDs in cookies can be used to hijack sessions of other users.
The above shows the session key in the cookie.
Attack prevention
To prevent such attacks, you need to filter user input before the content is displayed on the page. Previously, we directly obtained comment content from the database and input it to the HTML stream. Rails provides the method H for filtering the content before output.
Ruby
<% @task.comments.each do |comment| %> <p><%= h(comment.content) %></p><% end %>
When loading the page, we can see that the script is no longer executed. The H method filters out the angle brackets ("<" and ">") (uses the escape characters such as HTML to mark the angle brackets) so that the content can be properly displayed.
Rails also providessanitize
You can set a whitelist. tags in the whitelist are not filtered out.
Another method to prevent attacks
Unlike content filtering before the browser displays the content, you can filter the data before storing the data in the database. In the controller, the H method is not feasible and can be implemented using CGI: escapehtml.
Ruby
def create @task = Task.find(params[:task_id]) @comment = @task.comments.new(params[:comment]) @comment.content = CGI::escapeHTML(params[:comment][:content]) @comment.save redirect_to task_path(@task) end
- Http://en.wikipedia.org/wiki/Session_hijacking
Original address: http://railscasts.com/episodes/27-cross-site-scripting? View = asciicast
Railscase27 Cross Site Scripting cross-site scripting attack