vmg / redcarpet

The safe Markdown parser, reloaded.
MIT License
4.99k stars 527 forks source link

How prevent XSS attack in attributes of html? #434

Closed MatrixFr closed 9 years ago

MatrixFr commented 9 years ago

If I try : markdown.render("This is bongos, indeed. < a href=\"test\" onclick=\"alert('test')\">test;") this will keep the onclick attribute and can became a break point.

How prevent this server side?

robin850 commented 9 years ago

Hi @Argorate,

Actually by default Redcarpet isn't safe for parsing users' inputs for instance. To prevent this kind of problem you have two different solutions.

The first one is to rely on the Redcarpet::Render::Safe object which has been designed for the sake of security. You can also enable options such as :escape_html or :filter_html along with the :safe_links_only one at your render object level so people can only generate HTML using Markdown syntax (which is mostly safe) and reference URLs that are considered safe.

The second one, if you want to keep the markup but make it safe, is to implement a custom render object which inherits from Redcarpet::Render::HTML (for instance) and use a HTML-parsing library that will make the document safe. For instance, Loofah ships with such feature. Here's an example:

require 'loofah'

class CustomRender < Redcarpet::Render::HTML
  def postprocess(document)
    Loofah.fragment(document).scrub!(:strip).to_s
  end
end

I'm giving it a close, thanks for spotting this!