Circumvent Rails CSRF Protection

There is a security-related bug in Ruby on Rails 2.1.x and all 2.2. pre-releases. The CSRF protection given by
the protect_from_forgery method may possibly be circumvented by a crafted request.

The problem is that Rails by design will not check the authenticity token if the request has certain content types that are typically not generated by browsers. According to the original security message, this list also includes “text/plain” which may be generated by browsers. This form data encoding roundup gives an overview of what can be generated by today’s browsers. See this changset for details of which content types will be checked.

Possible Exploit

The content type can be set with the enctype attribute in HTML forms:

<form method=”post” enctype=”text/plain” action=”<%= some_post_action_path(@var) %>”><%= submit_tag “Start” %></form>

This was found in this Lighthouse ticket. The original security message states that Rails does not parse the parameters for these requests. However, I was able to craft requests where all parameters where correctly parsed and used.

 

Temporary Solution

Users of 2.1.x releases are advised to insert the following code into a file in config/initializers/

Mime::Type.unverifiable_types.delete(:text)

Or you apply this patch for the 2.1.x releases. Users of Edge Rails should upgrade to the latest version.

 

Fixes

Fixes will be in Rails version 2.1.3 and 2.2.2.

Rails Security Guide and Book

That’s it, the Ruby on Rails Security guide is ready. It is available as a Rails manual at http://guides.rubyonrails.org/security.html and as a free e-book at https://rorsecurity.info/the-book/. The first batch of the new Rails Guides also includes 14 other quality manuals ranging from “Getting started”, routing, testing and debugging.

So far, the online version of the guide is one long page, I hope it will be seperated soon. Meanwhile you can read the e-book version of it. For those of you looking for a quick overview of good practice and countermeasures, scan the document for the fragments that are highlighted.

I will be officially announcing the Guide at the OWASP EU Summit in Portugal this week.

Header Injection And Response Splitting

I thought about the redirect_to method when I saw Ryan’s screencast of how to go back with redirect_to :back. That way the user will be redirected to the URL from the Referer header field, it’s the same as redirect_to request.referer. The Referer is a user-supplied value which is set by the browser or another user-agent. It should not be possible to spoof the Referer in an Ajax request, but some browsers seem to allow it (Firefox does not).

An attack on this is quite unlikely. However if the attacker manages to manipulate the Referer, the victim will be redirected to another site. This site may install malicious software on the victim’s computer through browser security holes. Or it could be a phishing site that asks the victim to enter his username and password.

Then I saw comment #11 which suggests to put the referer into a hidden field:

<%= hidden_field_tag :referer, (params[:referer] || request.env[‘HTTP_REFERER’]) %>

The hidden_field_tag method automatically escapes the value, so it is not vulnerable to XSS. However, be aware of XSS if you use the params otherwise.

More important is that you would use redirect_to params[:referer]. This is a very nice redirector for any URL you like. If the attacker sets the params[:referer] value by supplying the parameter to the site with the hidden_field_tag from above, the victim will be redirected to any desired page:

http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld

Header Injection

Then there is a another problem with user-supplied values in the HTTP headers: Header Injection. It seems that Ruby/Rails does not sanitize the parameter passed to redirect_to. That means the user may set any header field he likes:

http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld%0a%0dX-Header:+Hi!

Note that “%0d%0a” is URL-encoded for “\r\n” which is a carriage-return and line-feed in Ruby. So the resulting HTTP header will be:

HTTP/1.1 302 Moved Temporarily
(…)
Location: http://www.malicious.tld
X-Header: Hi!

And even if you allow the user to supply only parts of the target URL, the attacker may still overwrite the Location header field (and thus redirect to any site he wants):

http://www.yourapplication.com/controller/action?referer=path/at/your/app%0aLocation:+http://www.malicious.tld

Response Splitting

As Header Injection is possible, Response Splitting might be, too. In HTTP, the header block is followed by two carriage-return, line-feeds (CRLF) and the actual data (usually HTML). The idea of Response Splitting is to inject two CRLFs, followed by another response with malicious HTML. The response will be:

HTTP/1.1 302 Found [First standard 302 response]Date: Tue, 12 Apr 2005 22:09:07 GMT
Location:
Content-Type: text/html

HTTP/1.1 200 OK [Second New response created by attacker begins]Content-Type: text/html

<html><font color=red>hey</font></html> [Arbitary input by user is shown as the redirected page]Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html

Read the original article here. Under certain circumstances this would present the malicious HTML to the user. However, this seems to work with Keep-Alive connections, only (and many browsers are using one-time connections). But you can’t rely on this. In any case this is a serious bug, and you should update your Rails to version 2.0.5 or the soon-to-be-released 2.1.2.

New RedCloth security

RedCloth is a module for using Textile in Ruby. Textile is a simple text format that can be converted to HTML, eliminating the need to use HTML directly to create documents, blogs, or web pages.

The new version 4 promises to be faster and without the bugs from version 3. And indeed it feels more reliable and many of the earlier security concers have now been dealt with. For example:

RedCloth.new(“<script>alert(1)</script>”).to_html

now returns

&lt;script&gt;alert(1)&lt;/script&gt;

instead of

<script>alert(1)</script>

 

in earlier versions. And it’s good that it escapes the input instead of deleting malicious parts. I tried many examples from the XSS cheatsheet and hand-crafted ones. The result is that nearly no malicious parts get through. Yes nearly.

The <code> tag gets through:

RedCloth.new(‘<code onmouseover=”bad_code_here”>asdf</code>’, [:filter_html]).to_html
<code onmouseover=”bad_code_here”>asdf</code>

I’ve created a ticket for that.

Also remember that CSS injection will work in textile, if you allow styles. See the earlier post for that.

Nevertheless the new version is far better. And in combination with a whitelist (namely Rails’ sanitize() method) it is even secure.

SQL Injection issue in :limit and :offset parameter

An SQL Injection vulnerability has been found in Rails. The issue affects Rails < 2.1.1, namely the :limit and :offset parameters that are not correctly sanitized:

 

Person.find(:all, :limit => “10; DROP TABLE users;”)

A possible attack will work only if you allow the user control these two values as in User.find(:all, :limit => 10, :offset => params[:offset]). Note that will_paginate is not affected, it escapes the values before.

This seemed to affect only PostgreSQL and SQLite as MySQL by default disallows multiple SQL statements. So you cannot drop a table. However, it could be used for information disclosure. Consider the UNION SQL statement:

User.find(:all, :limit => params[:limit])

params[:limit] #= “1 UNION (select 1,2,password,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,0 from users)”

 

What does this mean? The result is the full users table, with one small modification: One field contains the user’s password and the other fields are always a number between 0 and 9. Let’s assume the third column is the user’s first name and the application returns everything it found. This means an attacker may read the user’s password in the first name field. All he has to do is find out about the table names (take a look at the controller names), the column names (review the HTML source, guessing) and the number of columns in the table (try it). The UNION statement will work only if the second table has the same number of columns as the first one – hence the list of numbers.

Of course there might not be a password column in clear text, but this could be used to read any data from the database, or even other databases.

Countermeasures

  • Review your application whether you allow the user to control :limit or :offset
  • If you are on Rails 2.1.0, please apply this patch or get Rails 2.1.1
  • If you are on the Rails 2.0 or 1.2 branch, apply this backport patch

DoS vulnerability in REXML

Here is a security announcement for the REXML library (links by me) in the Ruby news:

There is a DoS vulnerability in the REXML library used by Rails to parse incoming XML requests. A so-called “XML entity explosion” attack technique can be used for remotely bringing down (disabling) any application which parses user-provided XML. Most Rails applications will be vulnerable to this attack.

Impact

An attacker can cause a denial of service by causing REXML to parse a document containing recursively nested entities such as:

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE member [
 <!ENTITY a “&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;”>
 <!ENTITY b “&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;”>
 <!ENTITY c “&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;”>
 <!ENTITY d “&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;”>
 <!ENTITY e “&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;”>
 <!ENTITY f “&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;”>
 <!ENTITY g “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”>
]>
<member>
&a;
</member>

M. Koziarski provides a Rails-specific solution to the problem:

The announcement contains details describing a monkeypatch which can
be applied to prevent the risk.  These instructions are reproduced
below with more rails specific information:

** Versions 2.0.2 and earlier

# Copy the fix file into RAILS_ROOT/lib
# Require the file from environment.rb require ‘rexml-expansion-fix’

** Versions 2.1.0 and edge

Copy the fix file into RAILS_ROOT/config/initializers, it will berequired automatically.

There is also a gem available which includes the fix file:

gem install rexml-expansion-fix

Once that command has completed add the following line to the bottom
of your environment.rb file:

require ‘rexml-expansion-fix’

Ruby security vulnerabilities

Here is the news from the Rails Log:

Drew Yao at Apple uncovered a handful of nasty security vulnerabilities affecting all current versions of Ruby. The details are still under wraps because an attacker can DoS you or possibly execute arbitrary code—holy crap! Better upgrade sooner than later.

According to the official Ruby security advisory, the vulnerable Rubies are:

  • 1.8.4 and earlier
  • 1.8.5-p230 and earlier
  • 1.8.6-p229 and earlier
  • 1.8.7-p21 and earlier

Those of us running Ruby 1.8.4 or earlier must upgrade to 1.8.5 or later for a fix. Those on 1.8.5-7 can grab the latest patchlevel release for a fix.

(Please note: Ruby 1.8.7 breaks backward compatibility and is only compatible with Rails 2.1 and later, so don’t go overboard!)

Automatic security

Security is not easy-to-use, not fancy and it is hard to remember all those nasty attack methods. So there are automatic security checks, firewalls, helpers and a lot more. They are built to make your application more secure. But automatic security tools can’t help you to find logic faults. What if you have a Cross-Site Scripting scanner that checks each and every field in your web application, but with a little knowledge, an attacker could change one id in the URL and he sees his neighbor’s confidential data.

BUT, automatic tools can be of great help, if you won’t solely rely on them. The SafeErb plugin reminds you to sanitize output, but it doesn’t do it automatically. A mass-assignment scanner might find this kind of security holes in you application. Or a web application firewall may protect holes you are not aware of. And, of course, security is a process and should be incorporated into the entire project life cycle.

That having said, I’d like to show you a nice web application firewall for your .htaccess, if you happen to use Apache. It comes from 0x000000.com, a whitehat hacker site, and it’s the result of seven years of server administration. It is not perfect, it is not especially for Rails applications or for your specific application, but it is definitely a good starting point. You can read the tutorial for explanation.

RewriteEngine On
Options +FollowSymLinks
ServerSignature Off

RewriteCond %{REQUEST_METHOD}  ^(HEAD|TRACE|DELETE|TRACK) [NC,OR]RewriteCond %{THE_REQUEST}     ^.*(\\r|\\n|%0A|%0D).* [NC,OR]

RewriteCond %{HTTP_REFERER}    ^(.*)(<|>|’|%0A|%0D|%27|%3C|%3E|%00).* [NC,OR]RewriteCond %{HTTP_COOKIE}     ^.*(<|>|’|%0A|%0D|%27|%3C|%3E|%00).* [NC,OR]RewriteCond %{REQUEST_URI}     ^/(,|;|:|<|>|”>|”<|/|\\\.\.\\).{0,9999}.* [NC,OR]

RewriteCond %{HTTP_USER_AGENT} ^$ [OR]RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|scan).* [NC,OR]RewriteCond %{HTTP_USER_AGENT} ^.*(<|>|’|%0A|%0D|%27|%3C|%3E|%00).* [NC,OR]

RewriteCond %{QUERY_STRING}    ^.*(;|<|>|’|”|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|cast|set
|declare|drop|update|md5|benchmark).* [NC,OR]RewriteCond %{QUERY_STRING}    ^.*(localhost|loopback|127\.0\.0\.1).* [NC,OR]RewriteCond %{QUERY_STRING}    ^.*\.[A-Za-z0-9].* [NC,OR]RewriteCond %{QUERY_STRING}    ^.*(<|>|’|%0A|%0D|%27|%3C|%3E|%00).* [NC]

RewriteRule ^(.*)$ access_log.php