CSC/ECE 517 Fall 2014/ch1a 23 ss: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(93 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= '''Security Features in Rails 4.x''' =
= '''Security Features in Rails 4.x''' =


This wiki aims to highlight all the security features in a popular web application framework: Rails 4.x


Web applications can be challenging for a developer to properly secure against threats. There are many attack vectors against web applications that must be carefully considered and mitigated. The developer must be responsible to understand these threats and take the necessary steps to secure the application and data.  A web application may be vulnerable due to misconfiguration, poorly written code, or through un-patched vulnerabilities.
[http://rubyonrails.org/ Ruby on Rails], or just Rails, is a web application framework written in [https://www.ruby-lang.org/ Ruby]. It is a full-stack framework which attempts to make the development process easier and more accessible. This wiki aims to highlight all the security features in a Rails 4.x.


__TOC__
__TOC__


= Threats Against Web Applications =
= Threats Against Web Applications =
Web applications are very open and susceptible to many types of attacks. Many of these attacks can be carried out anonymously and constantly. A web application developer must be vigilant in understanding the threats that exist, and the proper techniques to mitigate them.
==Cookie Management==
[http://en.wikipedia.org/wiki/HTTP_cookie Cookies] are used to maintain stateful sessions in [http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol HTTP]. The cookies typically contain the user's session id which is used to identify the user. By stealing it, the attacker can use the application in the victim's name.
More over since the data is stored on the client machine, programmers should not store sensitive data in cookies.
The cookie is sent in the clear and so the easiest way for the attacker is to sniff the packets. This attack is shown below in Figure 1.[[File:cookie_sniffing.png|none]]
Figure1: Packet Sniffing Attack
To manage the cookies Rails provide several options to the programmer.
===Use SSL===
[http://en.wikipedia.org/wiki/Transport_Layer_Security SSL] prevents the attacker from sniffing the cookie from the network.
<pre>
config.force_ssl = true
</pre>
===New Session Identifier===
Configure Rails to issue a new session identifier and declare the old one invalid after a successful login.
===Fast Timeout===
Set the expiry time stamp of the cookie to a small value so that chances of attacker using a stale cookie is minimized.
===Improved Cookie Serializer(Rails 4.x) ===
Earlier versions of Rails had a bug where serializing the cookie hash could cause remote code execution. This could happen if the attacker got hold of the application secret. Version 4.1 added a smarter serializer that will '''not''' recreate complex objects besides Strings, Integers and other JSON data types. This also prevents the bad practice of placing more complex objects in the session that can’t be completely restored by the JSON serializer.
==Injection ==
An attacker can inject client site executable code. When the victim renders it, it can steal the cookie, hijack the session and redirect the victim to a different page.
Injection can be a script, sql statement, ajax code or header injection. Though the root cause is poor programming, Rails provide various plug ins that allow the programmer to avoid it.
==== Cross Site Scripting (XSS) <ref>https://www.acunetix.com/websitesecurity/xss/</ref>====
[http://en.wikipedia.org/wiki/Cross-site_scripting XSS] is an attack where an adversary places client-side code in the web application, often through a valid method such as posting to a message board. This code is then viewed by other application users and executed by their client machines.
The general form of XSS attack is show below in Figure2.
[[File:Xss.png|none]]
Figure2: XSS attack in progress
This attack is mitigated by properly sanitizing any input to the application. <ref>https://www.netsparker.com/blog/web-security/ruby-on-rails-security-basics/</ref> The sanitize method may be used to strip improper code from user input.
'''Input to be sanitized''':
<pre><%= sanitize '<img src=x onerror=prompt(1)>' %></pre>


The threats against web applications include
'''Sanitized output:'''
==user account hijacking==
<pre>
==bypass of access control==
<img src=“x”>
==reading or modifying sensitive data==
</pre>
==presenting fraudulent content==
== Trojan horse ==


= Security Enhancements =
==== SQL Injection ====
== CSRF via Leaky #match Routes ==
 
== Regular Expression Anchors in Format Validations ==
SQL injection is a very common and serious vulnerability for many applications. The generalized concept is to pass carefully crafted input that will eventually get passed as parameters in a SQL statement. In July of 2014, Rails developers released version 4.1.3 in order to patch a serious vulnurability affecting applications using a PostgreSQL database system. <ref>http://www.computerworld.com/article/2489654/malware-vulnerabilities/ruby-on-rails-patches-tackle-sql-injection-vulnerabilities.html</ref> This vulnerability allowed attackers to inject arbitrary SQL code into the affected Rails applications.
== Clickjacking ==
 
== User-Readable Sessions ==
To protect the application from this potential vulnerability, you should be careful when processing any SQL query that contains user submitted data. <ref>http://guides.rubyonrails.org/security.html</ref> The sanitize_SQL method may be used to remove improper characters.
 
==== Header Injection ====
 
HTTP request headers have various fields that are user supplied and may be manipulated with more or less effort. Programmer need to escape these header fields and avoid building partial headers based on user input. Rails provide a rich api that can be used to create the headers in a secure fashion.
 
==Cross Site Request Forgery (CSRF)==
This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands. This is shown below in Figure 3.
[[File:My_csrf.png|none]]
Figure 3: CSRF attack
 
To fix this the application needs to do the following:
 
===Security Token===
All non GET request should use a security token. Rails inserts this required security token that our site knows but other sites don't know. This is verified on the server. If the security token does not match then the session will be reset.
 
Enable this in the application controller.
 
<pre>
protect_from_forgery
</pre>
 
== Application Logic ==
There are certain common functionality that most applications need to implement. If these are not implemented correctly, then they can cause a security vulnerability. Rails provide plug ins that make the job easier to implement. Some common cases are discussed below.
 
===User Authentication===
Most web applications have to deal with user authorization and authentication. Hence it is up to the programmer to implement it correctly. Rails provide built in "''has_secure_password'' feature that stores the password in encrypted manner.
*Brute Force Attack
** Good Password: Ensure that the user password are "random" enough. Rails make it easy to define requirements for the password field in the model.
** Implement [http://en.wikipedia.org/wiki/CAPTCHA CAPTCHAs]:This is a challenge response test that determines that the response is not generated by a computer. Rails provide extensive API for implementing it.
*Logging:Rails should be configured to not put passwords into log files by using the followingn in applicatin controller.
<pre>
config.filter_parameters
</pre>
*Anchor Regular Expressions:Ruby has extensive options that can be used to anchor it at the line beginning and line end. Rails 4 also introduces a multiline option for validates_format_of.
 
===File Upload===
Many applications allow user to upload files. Use Rail plugin to handle unsafe file names and file upload.
 
===Command Line===
Ruby provides api like "''system(command, parameters)'' which passes command line parameters safely.
 
==Denial Of Service (DOS) Attack==
A DOS attack is any method used by an adversary that causes the service to no longer be available for legitimate users. One of the common way this attack occurs in Rails applications, is through the exploitation of memory leaks. Since Symbols are not garbage collected, it is possible to run out of memory if too many are created.<ref>http://brakemanscanner.org/docs/warning_types/denial_of_service/</ref>
 
The best mitigation for this threat is to never convert any user-input into Symbols. If necessary, this it should be done in a controlled manner through the use of a whitelist. [http://brakemanscanner.org/docs/introduction/ Brakeman] can be used to scan for this type of vulnerability.
 
= Rails Security Tools =
In this section, we examine techniques to improve to the security of Rails web applications.
==Automated Security Scanners==
There are a number of different security analysis tools available for Ruby on Rails applications.
 
*[http://brakemanscanner.org/docs/introduction/ Brakeman] is an open source, automated static-analysis scanner available for Rails developers. Brakeman scans the source code for misconfiguration, conformance to best practices, and other potential security issues.
 
*[https://github.com/codesake/codesake-dawn Codesake::Dawn] is another open source scanner for Rails applications. It attempts to detect the MVC architecture of your application to properly check the code base. Codesake scans for XSS scripting and SQL injection vulnerabilities.
 
*[https://github.com/LTe/scanny Scanny] is and open source security scanner for Rails source code. It works by parsing individual Ruby files and looking for suspicious patterns in them. Scanny produces a security report after completion.


= Unresolved Issues =
= Unresolved Issues =
There are a few unresolved issues in the current release of Rails. In this section, we examine and describe those concerns with instructions on methods to mitigate them.
== Verbose Servers Headers ==
== Verbose Servers Headers ==
The default web server for a Rails application is [http://en.wikipedia.org/wiki/WEBrick WEBrick]. It is a simple open source server that is not often used in production, but has a potential security vulnerability if used in a live application. WEBrick returns a verbose security header which returns the full version number of both WEBrick and Ruby. <ref>http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/</ref>
Example HTTP Response:<ref>http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/</ref>
<pre>
HTTP/1.1 200 OK
# …
Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-04-20)
</pre>
This verbose message is unnecessary and provides too much information to a potential intruder. An adversary can easily scan many web applications looking for un-patched servers that may be exploited.
== Binding to 0.0.0.0 ==
== Binding to 0.0.0.0 ==
By default when starting a Rails server, it will bind to ''http://0.0.0.0:3000''. For a development environment, this is often unnecessary and only needs to bind to ''127.0.0.1''. Developers should use the ''--binding'' option to limit the interfaces to only those that are necessary.
== Versioned Secret Tokens ==
== Versioned Secret Tokens ==
== Logging Values in SQL statements ==
In Rails applications up through version 4.0, a generated secret security token was created in ''config/initializers/secret_token.rb'' when creating a Rails application. This token was vulnerable to being left unsecured by developers, or accidentally getting committed to a version control system. An adversary who obtained the secret token could trivially exploit the web application.
== Offsite Redirects ==
 
These concerns were alleviated in Ruby 4.1. The secret token file was replaced by a ''secrets.yml'' file in the config folder.
 
'''secrets.yml:'''
<pre>
development:
  secret_key_base:
test:
  secret_key_base:
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
</pre>
 
This provides the ability to store your sensitive tokens in an environment variable for better security. The ''secrets.yml'' file is also in .gitignore by default, which helps out unaware programmers from accidentally committing their key.


= Reference =
= Reference =
http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/
 
<references />

Latest revision as of 22:41, 25 September 2014

Security Features in Rails 4.x

Web applications can be challenging for a developer to properly secure against threats. There are many attack vectors against web applications that must be carefully considered and mitigated. The developer must be responsible to understand these threats and take the necessary steps to secure the application and data. A web application may be vulnerable due to misconfiguration, poorly written code, or through un-patched vulnerabilities.

Ruby on Rails, or just Rails, is a web application framework written in Ruby. It is a full-stack framework which attempts to make the development process easier and more accessible. This wiki aims to highlight all the security features in a Rails 4.x.

Threats Against Web Applications

Web applications are very open and susceptible to many types of attacks. Many of these attacks can be carried out anonymously and constantly. A web application developer must be vigilant in understanding the threats that exist, and the proper techniques to mitigate them.

Cookie Management

Cookies are used to maintain stateful sessions in HTTP. The cookies typically contain the user's session id which is used to identify the user. By stealing it, the attacker can use the application in the victim's name. More over since the data is stored on the client machine, programmers should not store sensitive data in cookies.

The cookie is sent in the clear and so the easiest way for the attacker is to sniff the packets. This attack is shown below in Figure 1.

Figure1: Packet Sniffing Attack

To manage the cookies Rails provide several options to the programmer.

Use SSL

SSL prevents the attacker from sniffing the cookie from the network.

config.force_ssl = true

New Session Identifier

Configure Rails to issue a new session identifier and declare the old one invalid after a successful login.

Fast Timeout

Set the expiry time stamp of the cookie to a small value so that chances of attacker using a stale cookie is minimized.

Improved Cookie Serializer(Rails 4.x)

Earlier versions of Rails had a bug where serializing the cookie hash could cause remote code execution. This could happen if the attacker got hold of the application secret. Version 4.1 added a smarter serializer that will not recreate complex objects besides Strings, Integers and other JSON data types. This also prevents the bad practice of placing more complex objects in the session that can’t be completely restored by the JSON serializer.

Injection

An attacker can inject client site executable code. When the victim renders it, it can steal the cookie, hijack the session and redirect the victim to a different page.

Injection can be a script, sql statement, ajax code or header injection. Though the root cause is poor programming, Rails provide various plug ins that allow the programmer to avoid it.

Cross Site Scripting (XSS) <ref>https://www.acunetix.com/websitesecurity/xss/</ref>

XSS is an attack where an adversary places client-side code in the web application, often through a valid method such as posting to a message board. This code is then viewed by other application users and executed by their client machines.

The general form of XSS attack is show below in Figure2.

Figure2: XSS attack in progress This attack is mitigated by properly sanitizing any input to the application. <ref>https://www.netsparker.com/blog/web-security/ruby-on-rails-security-basics/</ref> The sanitize method may be used to strip improper code from user input.

Input to be sanitized:

<%= sanitize '<img src=x onerror=prompt(1)>' %>

Sanitized output:

<img src=“x”>

SQL Injection

SQL injection is a very common and serious vulnerability for many applications. The generalized concept is to pass carefully crafted input that will eventually get passed as parameters in a SQL statement. In July of 2014, Rails developers released version 4.1.3 in order to patch a serious vulnurability affecting applications using a PostgreSQL database system. <ref>http://www.computerworld.com/article/2489654/malware-vulnerabilities/ruby-on-rails-patches-tackle-sql-injection-vulnerabilities.html</ref> This vulnerability allowed attackers to inject arbitrary SQL code into the affected Rails applications.

To protect the application from this potential vulnerability, you should be careful when processing any SQL query that contains user submitted data. <ref>http://guides.rubyonrails.org/security.html</ref> The sanitize_SQL method may be used to remove improper characters.

Header Injection

HTTP request headers have various fields that are user supplied and may be manipulated with more or less effort. Programmer need to escape these header fields and avoid building partial headers based on user input. Rails provide a rich api that can be used to create the headers in a secure fashion.

Cross Site Request Forgery (CSRF)

This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands. This is shown below in Figure 3.

Figure 3: CSRF attack

To fix this the application needs to do the following:

Security Token

All non GET request should use a security token. Rails inserts this required security token that our site knows but other sites don't know. This is verified on the server. If the security token does not match then the session will be reset.

Enable this in the application controller.

protect_from_forgery

Application Logic

There are certain common functionality that most applications need to implement. If these are not implemented correctly, then they can cause a security vulnerability. Rails provide plug ins that make the job easier to implement. Some common cases are discussed below.

User Authentication

Most web applications have to deal with user authorization and authentication. Hence it is up to the programmer to implement it correctly. Rails provide built in "has_secure_password feature that stores the password in encrypted manner.

  • Brute Force Attack
    • Good Password: Ensure that the user password are "random" enough. Rails make it easy to define requirements for the password field in the model.
    • Implement CAPTCHAs:This is a challenge response test that determines that the response is not generated by a computer. Rails provide extensive API for implementing it.
  • Logging:Rails should be configured to not put passwords into log files by using the followingn in applicatin controller.
config.filter_parameters
  • Anchor Regular Expressions:Ruby has extensive options that can be used to anchor it at the line beginning and line end. Rails 4 also introduces a multiline option for validates_format_of.

File Upload

Many applications allow user to upload files. Use Rail plugin to handle unsafe file names and file upload.

Command Line

Ruby provides api like "system(command, parameters) which passes command line parameters safely.

Denial Of Service (DOS) Attack

A DOS attack is any method used by an adversary that causes the service to no longer be available for legitimate users. One of the common way this attack occurs in Rails applications, is through the exploitation of memory leaks. Since Symbols are not garbage collected, it is possible to run out of memory if too many are created.<ref>http://brakemanscanner.org/docs/warning_types/denial_of_service/</ref>

The best mitigation for this threat is to never convert any user-input into Symbols. If necessary, this it should be done in a controlled manner through the use of a whitelist. Brakeman can be used to scan for this type of vulnerability.

Rails Security Tools

In this section, we examine techniques to improve to the security of Rails web applications.

Automated Security Scanners

There are a number of different security analysis tools available for Ruby on Rails applications.

  • Brakeman is an open source, automated static-analysis scanner available for Rails developers. Brakeman scans the source code for misconfiguration, conformance to best practices, and other potential security issues.
  • Codesake::Dawn is another open source scanner for Rails applications. It attempts to detect the MVC architecture of your application to properly check the code base. Codesake scans for XSS scripting and SQL injection vulnerabilities.
  • Scanny is and open source security scanner for Rails source code. It works by parsing individual Ruby files and looking for suspicious patterns in them. Scanny produces a security report after completion.

Unresolved Issues

There are a few unresolved issues in the current release of Rails. In this section, we examine and describe those concerns with instructions on methods to mitigate them.

Verbose Servers Headers

The default web server for a Rails application is WEBrick. It is a simple open source server that is not often used in production, but has a potential security vulnerability if used in a live application. WEBrick returns a verbose security header which returns the full version number of both WEBrick and Ruby. <ref>http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/</ref>

Example HTTP Response:<ref>http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/</ref>

HTTP/1.1 200 OK
# …
Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-04-20)

This verbose message is unnecessary and provides too much information to a potential intruder. An adversary can easily scan many web applications looking for un-patched servers that may be exploited.

Binding to 0.0.0.0

By default when starting a Rails server, it will bind to http://0.0.0.0:3000. For a development environment, this is often unnecessary and only needs to bind to 127.0.0.1. Developers should use the --binding option to limit the interfaces to only those that are necessary.

Versioned Secret Tokens

In Rails applications up through version 4.0, a generated secret security token was created in config/initializers/secret_token.rb when creating a Rails application. This token was vulnerable to being left unsecured by developers, or accidentally getting committed to a version control system. An adversary who obtained the secret token could trivially exploit the web application.

These concerns were alleviated in Ruby 4.1. The secret token file was replaced by a secrets.yml file in the config folder.

secrets.yml:

development:
  secret_key_base:
 
test:
  secret_key_base:
 
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

This provides the ability to store your sensitive tokens in an environment variable for better security. The secrets.yml file is also in .gitignore by default, which helps out unaware programmers from accidentally committing their key.

Reference

<references />