SlideShare a Scribd company logo
Heiko Webers, bauland42


Ruby on Rails Security Updated
Heiko Webers




 CEO of bauland42: Secure and innovative web
  applications, security code audits:
  http://www.bauland42.de http://www.werkstatt42.de
 Ruby on Rails Security Project: Blog and Book
  at http://www.rorsecurity.info
Cross-Site Scripting in Rails 3
   Before: <%= h @project.name %>
    @project.name #=> <script>
    h(@project.name) #=> &lt;script&gt;

   After: <%= @project.name %>

   Unless you want to allow HTML/JS:
     <%= raw @project.name %>
Cross-Site Scripting in Rails 3
 @project.name.html_safe? #=> false
 h(@project.name).html_safe? #=> true
 link_to(...).html_safe? #=> true
 "<br />".html_safe # => "<br />"




                                         4
Cross-Site Scripting in Rails 3
 safe + safe = safe
 safe.concat(safe) = safe
 (safe << safe) = safe


   safe + unsafe = unsafe
    ...



                                  5
Cross-Site Scripting in Rails 3
 String interpolation
 <%= "#{link_to(@product.title, @product)}
  #{link_to(@product.title, @product)}" %>
 Deliberately unsafe




                                              6
Cross-Site Scripting in Rails 3
   textilize() and simple_format() do not return
    safe strings
    textilize(‘*bold*‘) #=><strong>bold</strong>

 <%= textilize(@product.description) %>
 NO <%=raw textilize(@product.description)%>
 OK <%=sanitize textilize(@product.description)
  %>

                                                7
Cross-Site Scripting in Rails 3
 Know what you‘re doing
 <%= auto_link(@product.description) %>
  # => unsafe, so escaped
 <%= raw auto_link(@product.description) %>
  # => safe, but may contain HTML
 sanitize() it




                                           8
Cross-Site Scripting in Rails 3
 Know what you‘re doing
 Strings aren't magic:
  value = sanitize(@product.description)
  value.html_safe? #=> true
  value.gsub!(/--product_name--/, @product.title)
  value.html_safe? #=> true
  <%= value %>



                                               9
Cross-Site Scripting in Rails 3
 Rails helper are becoming stable now
 There were problems with content_tag(), tag(),
  submit_tag(), ...
 SafeErb plugin doesn‘t work yet/anymore




                                              10
Cross-Site Scripting in Rails 3
 xml.instruct!
  xml.description do
   xml << "The description: "
   xml << @product.description
  end
 Use xml.description @product.description to
  automatically escape



                                                11
Ajax and XSS
 No automatic escaping in RJS templates
 page.replace_html :notice,
   "Updated product #{@product.title}"




                                           12
Sanitization
 Don‘t write it on your own:
  value = self.description.gsub("<script>", "")
  <scr<script>ipt>
 sanitize(), strip_tags(), ... use the
  HTML::Tokenizer
 Based on regular expressions
 Doesn‘t always render valid HTML
 Last vulnerability in Rails 2.3.5 regarding non-
  printable ascii characters
                                                 13
Sanitization
 Use parsers like Nokogiri or Woodstox (JRuby)
 Gem sanitize: http://github.com/rgrove/sanitize
  Sanitize.clean(unsafe_html)
 Gem Loofah: http://github.com/flavorjones/
  loofah
  Loofah.fragment(unsafe_html).scrub!(:strip)




                                               14
Sql-Injection in Rails 3
 No find() anymore, no :conditions hash, ...
  But: Product.find(params[:id])
 User.order('users.id DESC').limit(20).all
 NO: Product.where("id = #{params[:id]}")
 Product.where(["id = ?", params[:id]])
 Product.where({:id => params[:id]})




                                                15
Sql-Injection in Rails 3
 NO: User.order(params[:order]).all
 raise "SQLi" unless ["id asc", "id desc"].include?
  (params[:order])
 Escape it yourself:
  Product.order(Product.connection.quote(params
  [:order])).all




                                                  16
Other changes in Rails 3
 config/initializers/session_store.rb
  Rails.application.config.session_store
  :cookie_store, :key => "_app_name_session"
 config/initializers/cookie_verification_secret.rb
  Rails.application.config.cookie_secret =
  'somereallylongrandomkey'
 Don‘t keep it in your SCM




                                                      17
Other changes in Rails 3
   Keep a value in a signed cookie:
    cookies.signed[:discount] = "12"

 filter_parameter_logging deprecated
 config.filter_parameters << :password
  in config/application.rb




                                          18
Respond_with in Rails 3
 class ProductsController < ApplicationController
    respond_to :html, :xml, :json
    def index
      respond_with(@products = Product.all)
    end
  end
 How to define what attributes to render in XML?
  @product.to_xml(:only => [:id])


                                                19
Bits and pieces
 You can deploy with a SSH key:
  ssh_options[:keys] = ["/path/to/id_rsa.ppk"]
 Secure the admin panel with a client SSL
  certificate
 Remove secrets from your SCM: database.yml,
  ssh_config.rb




                                             20
Bits and pieces
 Check what they‘re downloading
  File.dirname(requested_filename) ==
   expected_directory
 /download?file=../config/database.yml
 validates_format_of :filename,
  :with => /^[a-z.]+$/i
 hello.txt
  <script>alert(1)</script>
 Use A and z
                                          21
Privilege escalation
 def update
 @doc = Doc.find(params[:id])
 end


 before_filter :load_project
 before_filter :deny_if_not_full_access
 before_filter :load_doc
   @doc = @project.docs.find(params[:id])
 before_filter :deny_if_no_access_to_doc



                                            22
Authorization
 def deny_if_no_access_to_doc
 @doc.may_edit?(current_user)
 end


 def may_edit?(usr)
 self.creator == usr
 end


   <%= link_to(“Edit“,...) if @doc.may_edit?
    (current_user) %>

                                                23
That‘s it
 Questions?
 42@bauland42.de




                    24

More Related Content

PDF
Building Web Interface On Rails
PDF
Rails Best Practices
PPT
General Principles of Web Security
PDF
Rails 3 Beautiful Code
PDF
Rails 3 overview
PDF
Migrating legacy data
PDF
Rails Best Practices
PPTX
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
Building Web Interface On Rails
Rails Best Practices
General Principles of Web Security
Rails 3 Beautiful Code
Rails 3 overview
Migrating legacy data
Rails Best Practices
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato

What's hot (20)

PDF
Rails Security
KEY
CodeIgniter 3.0
PPTX
Asp.net identity 2.0
PDF
Workshop 8: Templating: Handlebars, DustJS
PPTX
Introduction to ASP.Net Viewstate
PDF
Sql Injection Myths and Fallacies
PDF
Workshop 27: Isomorphic web apps with ReactJS
PDF
Angular 2 introduction
PDF
&lt;img src="../i/r_14.png" />
KEY
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
PDF
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
PDF
The JavaFX Ecosystem
PDF
Practical Protocol-Oriented-Programming
PPTX
ASP.NET MVC 4 - Routing Internals
KEY
25 Real Life Tips In Ruby on Rails Development
PDF
Idoc script beginner guide
PDF
Trustparency web doc spring 2.5 & hibernate
PDF
Html server control - ASP. NET with c#
PDF
Practical JavaScript Programming - Session 8/8
PDF
The Rails Way
Rails Security
CodeIgniter 3.0
Asp.net identity 2.0
Workshop 8: Templating: Handlebars, DustJS
Introduction to ASP.Net Viewstate
Sql Injection Myths and Fallacies
Workshop 27: Isomorphic web apps with ReactJS
Angular 2 introduction
&lt;img src="../i/r_14.png" />
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
The JavaFX Ecosystem
Practical Protocol-Oriented-Programming
ASP.NET MVC 4 - Routing Internals
25 Real Life Tips In Ruby on Rails Development
Idoc script beginner guide
Trustparency web doc spring 2.5 & hibernate
Html server control - ASP. NET with c#
Practical JavaScript Programming - Session 8/8
The Rails Way
Ad

Similar to Ruby on Rails Security Updated (Rails 3) at RailsWayCon (20)

PDF
Rails 3 : Cool New Things
PDF
Rails3 changesets
PDF
Rails Security
ZIP
Rails 3 (beta) Roundup
PDF
Ruby on-rails-security
PDF
Rails for Beginners - Le Wagon
PDF
Ruby on Rails Security
PDF
Ruby on Rails Security
PDF
Rails入門與新人實戰經驗分享
PDF
Ruby On Rails Security 9984
PPT
Migrating PriceChirp to Rails 3.0: The Pain Points
PDF
Migrating Legacy Rails Apps to Rails 3
KEY
Rails 3.1
PDF
Ruby on Rails - The Best Track for your Start Up
PDF
My rails way
PDF
Agile Web Development With Rails Third Edition Third Ruby Sam
PDF
Rails 4.0
KEY
Rapid development with Rails
ODP
Migration from Rails2 to Rails3
PDF
Rails 3 hints
Rails 3 : Cool New Things
Rails3 changesets
Rails Security
Rails 3 (beta) Roundup
Ruby on-rails-security
Rails for Beginners - Le Wagon
Ruby on Rails Security
Ruby on Rails Security
Rails入門與新人實戰經驗分享
Ruby On Rails Security 9984
Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating Legacy Rails Apps to Rails 3
Rails 3.1
Ruby on Rails - The Best Track for your Start Up
My rails way
Agile Web Development With Rails Third Edition Third Ruby Sam
Rails 4.0
Rapid development with Rails
Migration from Rails2 to Rails3
Rails 3 hints
Ad

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Approach and Philosophy of On baking technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
Teaching material agriculture food technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectral efficient network and resource selection model in 5G networks
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
20250228 LYD VKU AI Blended-Learning.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
Dropbox Q2 2025 Financial Results & Investor Presentation
Approach and Philosophy of On baking technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Review of recent advances in non-invasive hemoglobin estimation
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Teaching material agriculture food technology
Encapsulation_ Review paper, used for researhc scholars
Unlocking AI with Model Context Protocol (MCP)
The Rise and Fall of 3GPP – Time for a Sabbatical?
Advanced methodologies resolving dimensionality complications for autism neur...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Monthly Chronicles - July 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

Ruby on Rails Security Updated (Rails 3) at RailsWayCon

  • 1. Heiko Webers, bauland42 Ruby on Rails Security Updated
  • 2. Heiko Webers  CEO of bauland42: Secure and innovative web applications, security code audits: http://www.bauland42.de http://www.werkstatt42.de  Ruby on Rails Security Project: Blog and Book at http://www.rorsecurity.info
  • 3. Cross-Site Scripting in Rails 3  Before: <%= h @project.name %> @project.name #=> <script> h(@project.name) #=> &lt;script&gt;  After: <%= @project.name %>  Unless you want to allow HTML/JS: <%= raw @project.name %>
  • 4. Cross-Site Scripting in Rails 3  @project.name.html_safe? #=> false  h(@project.name).html_safe? #=> true  link_to(...).html_safe? #=> true  "<br />".html_safe # => "<br />" 4
  • 5. Cross-Site Scripting in Rails 3  safe + safe = safe  safe.concat(safe) = safe  (safe << safe) = safe  safe + unsafe = unsafe ... 5
  • 6. Cross-Site Scripting in Rails 3  String interpolation  <%= "#{link_to(@product.title, @product)} #{link_to(@product.title, @product)}" %>  Deliberately unsafe 6
  • 7. Cross-Site Scripting in Rails 3  textilize() and simple_format() do not return safe strings textilize(‘*bold*‘) #=><strong>bold</strong>  <%= textilize(@product.description) %>  NO <%=raw textilize(@product.description)%>  OK <%=sanitize textilize(@product.description) %> 7
  • 8. Cross-Site Scripting in Rails 3  Know what you‘re doing  <%= auto_link(@product.description) %> # => unsafe, so escaped  <%= raw auto_link(@product.description) %> # => safe, but may contain HTML  sanitize() it 8
  • 9. Cross-Site Scripting in Rails 3  Know what you‘re doing  Strings aren't magic: value = sanitize(@product.description) value.html_safe? #=> true value.gsub!(/--product_name--/, @product.title) value.html_safe? #=> true <%= value %> 9
  • 10. Cross-Site Scripting in Rails 3  Rails helper are becoming stable now  There were problems with content_tag(), tag(), submit_tag(), ...  SafeErb plugin doesn‘t work yet/anymore 10
  • 11. Cross-Site Scripting in Rails 3  xml.instruct! xml.description do xml << "The description: " xml << @product.description end  Use xml.description @product.description to automatically escape 11
  • 12. Ajax and XSS  No automatic escaping in RJS templates  page.replace_html :notice, "Updated product #{@product.title}" 12
  • 13. Sanitization  Don‘t write it on your own: value = self.description.gsub("<script>", "") <scr<script>ipt>  sanitize(), strip_tags(), ... use the HTML::Tokenizer  Based on regular expressions  Doesn‘t always render valid HTML  Last vulnerability in Rails 2.3.5 regarding non- printable ascii characters 13
  • 14. Sanitization  Use parsers like Nokogiri or Woodstox (JRuby)  Gem sanitize: http://github.com/rgrove/sanitize Sanitize.clean(unsafe_html)  Gem Loofah: http://github.com/flavorjones/ loofah Loofah.fragment(unsafe_html).scrub!(:strip) 14
  • 15. Sql-Injection in Rails 3  No find() anymore, no :conditions hash, ... But: Product.find(params[:id])  User.order('users.id DESC').limit(20).all  NO: Product.where("id = #{params[:id]}")  Product.where(["id = ?", params[:id]])  Product.where({:id => params[:id]}) 15
  • 16. Sql-Injection in Rails 3  NO: User.order(params[:order]).all  raise "SQLi" unless ["id asc", "id desc"].include? (params[:order])  Escape it yourself: Product.order(Product.connection.quote(params [:order])).all 16
  • 17. Other changes in Rails 3  config/initializers/session_store.rb Rails.application.config.session_store :cookie_store, :key => "_app_name_session"  config/initializers/cookie_verification_secret.rb Rails.application.config.cookie_secret = 'somereallylongrandomkey'  Don‘t keep it in your SCM 17
  • 18. Other changes in Rails 3  Keep a value in a signed cookie: cookies.signed[:discount] = "12"  filter_parameter_logging deprecated  config.filter_parameters << :password in config/application.rb 18
  • 19. Respond_with in Rails 3  class ProductsController < ApplicationController respond_to :html, :xml, :json def index respond_with(@products = Product.all) end end  How to define what attributes to render in XML? @product.to_xml(:only => [:id]) 19
  • 20. Bits and pieces  You can deploy with a SSH key: ssh_options[:keys] = ["/path/to/id_rsa.ppk"]  Secure the admin panel with a client SSL certificate  Remove secrets from your SCM: database.yml, ssh_config.rb 20
  • 21. Bits and pieces  Check what they‘re downloading File.dirname(requested_filename) == expected_directory  /download?file=../config/database.yml  validates_format_of :filename, :with => /^[a-z.]+$/i  hello.txt <script>alert(1)</script>  Use A and z 21
  • 22. Privilege escalation  def update  @doc = Doc.find(params[:id])  end  before_filter :load_project  before_filter :deny_if_not_full_access  before_filter :load_doc @doc = @project.docs.find(params[:id])  before_filter :deny_if_no_access_to_doc 22
  • 23. Authorization  def deny_if_no_access_to_doc  @doc.may_edit?(current_user)  end  def may_edit?(usr)  self.creator == usr  end  <%= link_to(“Edit“,...) if @doc.may_edit? (current_user) %> 23
  • 24. That‘s it  Questions?  42@bauland42.de 24