Brakeman Warning: Unsafe parameter value in `link_to` href even after sanitizing the param

565 views Asked by At

I have the following code on my html.haml view:

= link_to params[:returnurl], class: "btn btn-secondary" do
    = fa_icon 'chevron-left', class: 'm-r-quarter', text: 'Cancel'

When I run brakeman, I get the following warning:

Confidence: High
Category: Cross-Site Scripting
Check: LinkToHref
Message: Unsafe parameter value in `link_to` href

Even after using sanitize as shown below, it is still giving me the same warning:

= link_to sanitize(params[:returnurl]), class: "btn btn-secondary" do
    = fa_icon 'chevron-left', class: 'm-r-quarter', text: 'Cancel'

I am very confused why am I still getting it and how would I resolve it. Thank you.

2

There are 2 answers

0
Mark Meyer On

There is generally not a safe with to create a link using a passed in parameter as the value for the href of the link.

Imagine a nefarious agent could send a link to your page where the returnurl param points to a site where they could phish from details of your user or the returnurl could use javascript: and then pass the user cookie data to their server and hijack the session.

You'll want to rethink the design of this so that it's not necessary to get the returnurl as a parameter. Ideally you can infer it from some other information. Storing the url in the users's session is an obfuscated option, but this could still be exploited.

0
Nick On

If you want to at least protect from javascript: or similar unsafe values, here's a method I added to my ApplicationHelper to ensure the URI scheme is http:

module ApplicationHelper
  def safe_url(url)
    uri = URI.parse(url)

    uri.to_s if uri.is_a?(URI::HTTP)
  rescue URI::InvalidURIError
    nil
  end
end

This won't protect against URLs with malicious content like Mark Meyer is referring to, but does add a bit of protection.