9

In an rails application, users can create events and post an url to link to the external event site.

How do I sanitize the urls to prevent XSS links?

Thanks in advance,

example of XSS, which is not preventable by rails' sanitize method

@url = "javascript:alert('XSS')"
<a href="<%=sanitize @url%>">test link</a>
rickypai
  • 4,016
  • 6
  • 26
  • 30

4 Answers4

6

Try sanitizing once the href is already in a tag like:

url = "javascript:alert('XSS')"
sanitize link_to('xss link', url)

This gives me:

<a>xss link</a>
Ben
  • 1,441
  • 4
  • 18
  • 20
3

You can use Rails' sanitize method for some basic restriction.

Or you can use rgrove's sanitize gem for more options.

Hope this helps.

Phyo Wai Win
  • 1,160
  • 6
  • 14
  • @url = "javascript:alert('XSS')" xss link does not work. i should reflect in my question that i have already tested the rails' sanitize method. – rickypai Mar 10 '12 at 05:47
  • 1
    rgrove's sanitize gem is really nice if you need more control than the built-in Rails sanitize gives you. Either way, like Ben's answer points out, you need to sanitize the html for the entire link, not just the URL itself. – antinome Nov 06 '13 at 16:40
2

sanitize works with html strings, not urls. meaning, you can't sanitize an URL itself, but you can sanitize a piece of html which has a link with an malicious url. for example

<%= sanitize "<a href='#{@url}'>Things</a>" %>

That will clean your link of all known malicious attributes

Nikolay
  • 1,392
  • 1
  • 9
  • 15
-2

This vulnerability has been fixed since 3.2.13, 3.1.12, 2.3.18 .

The following link also provides a patch you can use in earlier versions.

https://groups.google.com/forum/#!msg/rubyonrails-security/zAAU7vGTPvI/1vZDWXqBuXgJ