SlideShare a Scribd company logo
Rails Security




Jonathan Weiss, 30.10.2009
Peritor GmbH
Who am I ?


I work at    Peritor in Berlin

I tweet at   @jweiss

I code at    http://github.com/jweiss

I blog at    http://blog.innerewut.de




                                        2
Peritor
             Working on




          http://scalarium.com


                                 3
Agenda



                              Follow the application stack
                              and look for
 Setup and deployment


                            •  Information leaks
 Application code
                            •  Possible vulnerabilities
                            •  Security best practices
 Framework code


  Rails Application Stack




                                                             4

                                                                 4
Rails Application Setup




                          5
Rails Setup




              6
Rails Setup - FastCGI




                        7
Rails Setup - Mongrel




                        8
Rails Setup – mod_rails




                          9
Rails Setup – Unicorn




                        10
Information leaks
       and
  vulnerabilities




                    11
Information leaks

Is the target application a Rails application?
 •  Default setup for static files:
     /javascripts/application.js
     /stylesheets/application.css
     /images/foo.png


 •  URL schema
     /project/show/12
     /messages/create
     /folder/delete/43
     /users/83



                                                 12
Information leaks

Is the target application a Rails application?
 •  Rails provides default templates for 404 and 500 status pages
 •  Different Rails versions use different default pages
 •  422.html only present in applications generated with Rails >= 2.0
 •  Dispatcher files not present in recent Rails versions




                                                                        13
Sample Status Pages
  http://www.twitter.com/500.html     http://www.43people.com/500.html




 http://www.engineyard.com/500.html   Rails >= 1.2 status 500 page




                                                                         14
Server Header

GET http://www.haystack.com

Date: Wed, 28 Oct 2009 11:23:24 GMT
Server: nginx/0.6.32
Cache-Control: max-age=0, no-cache, no-store
…



GET https://signup.37signals.com/highrise/solo/signup/new

Date: Wed, 28 Oct 2009 11:54:24 GMT
Server: Apache
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 2.2.5
Status: 200 OK
…




                                                             15
Server Header

GET http://www.twitter.com

Date: Wed, 28 Oct 2009 11:23:24 GMT
Server: hi
Status: 200 OK
…



GET http://www.golfermail.org

Date: Wed, 28 Oct 2009 11:13:41 GMT
Server: Mongrel 1.1.5
Status: 200 OK
…
                                      Disable Server header
                                        # httpd.conf
                                        Header unset Server
                                        Header unset X-Powered-By




                                                                    16
Information leaks

Subversion metadata
  •  Typically Rails applications are deployed with Capistrano / Webistrano
  •  The default deployment will push .svn directories to the servers



GET http://www.strongspace.com/.svn/entries

…
dir
25376
http://svn.joyent.com/joyent/deprecated_repositories/www.strongspace/trunk/public
http://svn.joyent.com/joyent
                                                                            Prevent .svn download
2006-04-14T03:06:39.902218Z                                                     <DirectoryMatch "^/.*/.svn/">
34                                                                               ErrorDocument 403 /404.html
justin@joyent.com                                                                Order allow,deny
                                                                                 Deny from all
…
                                                                                 Satisfy All
                                                                                </DirectoryMatch>

                                                                                                                 17
Cookie Session Storage

Since Rails 2.0 the session data is stored in the cookie by default




Base64(CGI::escape(SESSION-DATA))--HMAC(secret_key, SESSION-DATA)




                                                                      18
Cookie Session Storage

Security implications
 •  The user can view the session data in plain text
 •  The HMAC can be brute-forced and arbitrary session data could be created
 •  Replay attacks are easier as you cannot flush the client-side session



Countermeasures
 •  Don’t store important data in the session!
 •  Use a strong password,
    Rails already forces at least 30 characters
 •  Invalidate sessions after certain time on the server side


 … or just switch to another session storage
                                                                               19
Cookie Session Storage

Rails default session secret




Set HTTPS only cookies




                               20
Cross-Site Scripting - XSS



“The injection of HTML or client-side Scripts (e.g. JavaScript) by malicious users into
web pages viewed by other users.”




                                                                                          21
Cross-Site Scripting - XSS


Cases of accepted user input
 •  No formatting allowed
    search query, user name, post title, …


 •  Formatting allowed
    post body, wiki page, …




                                             22
XSS - No Formatting Allowed (Rails 2.x)

Use the Rails `h()` helper to HTML escape user input




But using `h()` everywhere is easy to forget.
Better, use safeERB, XSS Shield, or rails_xss plugins:
    http://agilewebdevelopment.com/plugins/safe_erb
    http://code.google.com/p/xss-shield/
    http://github.com/NZKoz/rails_xss




                                                         23
XSS - No Formatting Allowed (Rails 3)

Rails 3 auto escapes strings in RHTML template




Explicitly mark strings as HTML safe




                                                 24
XSS - No Formatting Allowed (Rails 3)

rails_xss Plugin
 •  Build-in in Rails 3
 •  Introduces “Safe Buffer” concept
 •  Updates all the helpers to mark them as html_safe!
 •  Requires Erubis




 Install and get familiar with if on Rails 2.x
 http://github.com/NZKoz/rails_xss




                                                         25
XSS - Formatting Allowed

Two approaches


 Use custom tags that will translate to HTML (vBulletin tags, RedCloth, Textile, …)




 Use HTML and remove unwanted tags and attributes
    •  Blacklist - Rails 1.2
    •  Whitelist - Rails 2.0




                                                                                      26
XSS - Custom Tags

Relying on the external syntax is not really secure




              Filter HTML anyhow




                                                      27
XSS - HTML Filtering

Use the Rails `sanitize()` helper




Only effective with Rails > 2.0 (Whitelisting):
  •  Filters HTML nodes and attributes
  •  Removes protocols like “javascript:”
  •  Handles unicode/ascii/hex hacks



                                                  28
XSS - HTML Filtering

sanitize(html, options = {})




http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html

                                                                            29
XSS - HTML Filtering

Utilize Tidy if you want to be more cautious




                                               30
Session Fixation



Provide the user with a session that he shares with the attacker:




                                                                    31
Session Fixation

Rails uses only cookie-based sessions


Still, you should reset the session after a login




The popular authentication plugins like restful_authentication are not doing this!

                                                                                     32
Cross-Site Request Forgery - CSRF



You visit a malicious site which has an image like this




Only accepting POST does not really help




                                                          33
CSRF Protection in Rails



By default Rails > 2.0 will check all POST requests for a session token




All forms generated by Rails will supply this token

                                                                          34
CSRF Protection in Rails


Very useful and on-by-default, but make sure that
 •  GET requests are safe and idempotent
 •  Session cookies are not persistent (expires-at)




                                                      35
SQL Injection


The user’s input is not correctly escaped before using it in SQL statements




                                                                              36
SQL Injection Protection in Rails


Always use the escaped form




If you have to manually use a user-submitted value, use `quote()`




                                                                    37
SQL Injection Protection in Rails


Take care with Rails < 2.1




Limit and offset are only escaped in Rails >= 2.1
( MySQL special case )




                                                    38
JavaScript Hijacking

http://my.evil.site/




 JSON response




The JSON response will be evaled by the Browser’s JavaScript engine.
With a redefined `Array()` function this data can be sent back to http://my.evil.site
                                                                                       39
JavaScript Hijacking Prevention

 •  Don’t put important data in JSON responses
 •  Use unguessable URLs
 •  Use a Browser that does not support the redefinition of Array & co,
    currently only FireFox 3
 •  Don’t return a straight JSON response, prefix it with garbage:




The Rails JavaScript helpers don’t support prefixed JSON responses


                                                                         40
Mass Assignment

User model




                  41
Mass Assignment

Handling in Controller




A malicious user could just submit any value he wants




                                                        42
Mass Assignment

Use `attr_protected` and `attr_accessible`




                       Vs.




Start with `attr_protected` and migrate to `attr_accessible` because of the different
default policies for new attributes.



                                                                                        43
Rails Plugins

Re-using code through plugins is very popular in Rails


Plugins can have their problems too
 •  Just because somebody wrote and published a plugin it doesn’t mean the plugin is
    proven to be mature, stable or secure
 •  Popular plugins can also have security problems, e.g. restful_authentication
 •  Don’t use svn:externals to track external plugins,
    if the plugin’s home page is unavailable you cannot deploy your site




                                                                                       44
Rails Plugins

How to handle plugins
 •  Always do a code review of new plugins and look for obvious problems
 •  Track plugin announcements
 •  Track external sources with Piston, a wrapper around svn:externals




   http://piston.rubyforge.org/



                                                                           45
Conclusion




             46
Conclusion


 Rails has many security features enabled by default
    •  SQL quoting
    •  HTML sanitization
    •  CSRF protection


 The setup can be tricky to get right




 Rails is by no means a “web app security silver bullet” but adding security
  is easy and not a pain like in many other frameworks




                                                                               47
Questions?




             48
Peritor GmbH

Blücherstaße 22
10961 Berlin
Telefon: +49 (0)30 69 20 09 84 0
Telefax: +49 (0)30 69 20 09 84 9

Internet: www.peritor.com
E-Mail: kontakt@peritor.com




                                          49
Peritor GmbH - Alle Rechte vorbehalten        49

More Related Content

PDF
Ruby on Rails Security
PDF
Protecting Java EE Web Apps with Secure HTTP Headers
PDF
Hack Into Drupal Sites (or, How to Secure Your Drupal Site)
PDF
Web Server Hardening
ODP
Drupal Security Hardening
PDF
Secure Your Wordpress
PPSX
Selenium WebDriver
PDF
OpenSolaris Web Stack MySQL BOF
Ruby on Rails Security
Protecting Java EE Web Apps with Secure HTTP Headers
Hack Into Drupal Sites (or, How to Secure Your Drupal Site)
Web Server Hardening
Drupal Security Hardening
Secure Your Wordpress
Selenium WebDriver
OpenSolaris Web Stack MySQL BOF

What's hot (15)

PDF
Hack Proof Your Drupal Site
PDF
Slides Cassandra
PPTX
Whats new in ASP.NET 4.0
PDF
Introduction to MariaDb
PPTX
Oracle Database 12c Attack Vectors
PDF
CentOS Linux Server Hardening
PDF
Blackhat11 shreeraj reverse_engineering_browser
PDF
WildFly AppServer - State of the Union
PPTX
How to hack Citrix (So, You Just Inherited Someone Else's Citrix Environment....
PDF
Drupal and Security: What You Need to Know
PDF
MuleSoft ESB Payload Encrypt Decrypt using anypoint enterprise security
PDF
Mastering VMware Datacenter Part-1
PPT
FIND ME IF YOU CAN – SMART FUZZING AND DISCOVERY
PDF
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
PDF
Oracle vm 3.0 Fresh Start - Tarmo Alasoo
Hack Proof Your Drupal Site
Slides Cassandra
Whats new in ASP.NET 4.0
Introduction to MariaDb
Oracle Database 12c Attack Vectors
CentOS Linux Server Hardening
Blackhat11 shreeraj reverse_engineering_browser
WildFly AppServer - State of the Union
How to hack Citrix (So, You Just Inherited Someone Else's Citrix Environment....
Drupal and Security: What You Need to Know
MuleSoft ESB Payload Encrypt Decrypt using anypoint enterprise security
Mastering VMware Datacenter Part-1
FIND ME IF YOU CAN – SMART FUZZING AND DISCOVERY
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
Oracle vm 3.0 Fresh Start - Tarmo Alasoo
Ad

Similar to Rails Security (20)

PDF
Ruby on-rails-security
PDF
Ruby on Rails Security
PDF
Ruby On Rails Security 9984
PPTX
Cloudflare and Drupal - fighting bots and traffic peaks
PPTX
Html5 security
PDF
Anatomy of a Cloud Hack
PPTX
CS166 Final project
PDF
Play Framework and Activator
PPTX
Ruby on Rails Penetration Testing
PPTX
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
PDF
Watch How The Giants Fall: Learning from Bug Bounty Results
PDF
Veer's Container Security
PDF
DEF CON 24 - workshop - Craig Young - brainwashing embedded systems
PDF
Denis Baranov - Root via XSS
PDF
Security Goodness with Ruby on Rails
PDF
Rails Security
PPTX
Owning computers without shell access dark
PPTX
12 Ways Not to get 'Hacked' your Kubernetes Cluster
PPTX
"How to" Webinar: Sending Data to Sumo Logic
Ruby on-rails-security
Ruby on Rails Security
Ruby On Rails Security 9984
Cloudflare and Drupal - fighting bots and traffic peaks
Html5 security
Anatomy of a Cloud Hack
CS166 Final project
Play Framework and Activator
Ruby on Rails Penetration Testing
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
Watch How The Giants Fall: Learning from Bug Bounty Results
Veer's Container Security
DEF CON 24 - workshop - Craig Young - brainwashing embedded systems
Denis Baranov - Root via XSS
Security Goodness with Ruby on Rails
Rails Security
Owning computers without shell access dark
12 Ways Not to get 'Hacked' your Kubernetes Cluster
"How to" Webinar: Sending Data to Sumo Logic
Ad

More from Jonathan Weiss (20)

PDF
Docker on AWS OpsWorks
PDF
ChefConf 2014 - AWS OpsWorks Under The Hood
PDF
AWS OpsWorks & Chef at the Hamburg Chef User Group 2014
PPTX
DevOpsDays Amsterdam - Observations in the cloud
PDF
Amazon SWF and Gordon
PDF
Introduction to Backbone.js
PDF
Scalarium and CouchDB
PDF
Build your own clouds with Chef and MCollective
PDF
NoSQL - Motivation and Overview
PDF
NoSQL - An introduction to CouchDB
PDF
Running on Amazon EC2
PDF
Amazon EC2 in der Praxis
PDF
Infrastructure Automation with Chef
PDF
Rails in the Cloud
PDF
EventMachine
PDF
CouchDB on Rails
PDF
Rails in the Cloud - Experiences from running on EC2
PDF
CouchDB on Rails - RailsWayCon 2010
PDF
CouchDB on Rails - FrozenRails 2010
PDF
NoSQL - Post-Relational Databases - BarCamp Ruhr3
Docker on AWS OpsWorks
ChefConf 2014 - AWS OpsWorks Under The Hood
AWS OpsWorks & Chef at the Hamburg Chef User Group 2014
DevOpsDays Amsterdam - Observations in the cloud
Amazon SWF and Gordon
Introduction to Backbone.js
Scalarium and CouchDB
Build your own clouds with Chef and MCollective
NoSQL - Motivation and Overview
NoSQL - An introduction to CouchDB
Running on Amazon EC2
Amazon EC2 in der Praxis
Infrastructure Automation with Chef
Rails in the Cloud
EventMachine
CouchDB on Rails
Rails in the Cloud - Experiences from running on EC2
CouchDB on Rails - RailsWayCon 2010
CouchDB on Rails - FrozenRails 2010
NoSQL - Post-Relational Databases - BarCamp Ruhr3

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Electronic commerce courselecture one. Pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Chapter 3 Spatial Domain Image Processing.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Unlocking AI with Model Context Protocol (MCP)
The AUB Centre for AI in Media Proposal.docx
Empathic Computing: Creating Shared Understanding
Dropbox Q2 2025 Financial Results & Investor Presentation
MIND Revenue Release Quarter 2 2025 Press Release
Programs and apps: productivity, graphics, security and other tools
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Encapsulation_ Review paper, used for researhc scholars
The Rise and Fall of 3GPP – Time for a Sabbatical?
Electronic commerce courselecture one. Pdf
Assigned Numbers - 2025 - Bluetooth® Document
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Network Security Unit 5.pdf for BCA BBA.
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Chapter 3 Spatial Domain Image Processing.pdf

Rails Security

  • 1. Rails Security Jonathan Weiss, 30.10.2009 Peritor GmbH
  • 2. Who am I ? I work at Peritor in Berlin I tweet at @jweiss I code at http://github.com/jweiss I blog at http://blog.innerewut.de 2
  • 3. Peritor Working on http://scalarium.com 3
  • 4. Agenda Follow the application stack and look for Setup and deployment •  Information leaks Application code •  Possible vulnerabilities •  Security best practices Framework code Rails Application Stack 4 4
  • 7. Rails Setup - FastCGI 7
  • 8. Rails Setup - Mongrel 8
  • 9. Rails Setup – mod_rails 9
  • 10. Rails Setup – Unicorn 10
  • 11. Information leaks and vulnerabilities 11
  • 12. Information leaks Is the target application a Rails application? •  Default setup for static files: /javascripts/application.js /stylesheets/application.css /images/foo.png •  URL schema /project/show/12 /messages/create /folder/delete/43 /users/83 12
  • 13. Information leaks Is the target application a Rails application? •  Rails provides default templates for 404 and 500 status pages •  Different Rails versions use different default pages •  422.html only present in applications generated with Rails >= 2.0 •  Dispatcher files not present in recent Rails versions 13
  • 14. Sample Status Pages http://www.twitter.com/500.html http://www.43people.com/500.html http://www.engineyard.com/500.html Rails >= 1.2 status 500 page 14
  • 15. Server Header GET http://www.haystack.com Date: Wed, 28 Oct 2009 11:23:24 GMT Server: nginx/0.6.32 Cache-Control: max-age=0, no-cache, no-store … GET https://signup.37signals.com/highrise/solo/signup/new Date: Wed, 28 Oct 2009 11:54:24 GMT Server: Apache X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 2.2.5 Status: 200 OK … 15
  • 16. Server Header GET http://www.twitter.com Date: Wed, 28 Oct 2009 11:23:24 GMT Server: hi Status: 200 OK … GET http://www.golfermail.org Date: Wed, 28 Oct 2009 11:13:41 GMT Server: Mongrel 1.1.5 Status: 200 OK … Disable Server header # httpd.conf Header unset Server Header unset X-Powered-By 16
  • 17. Information leaks Subversion metadata •  Typically Rails applications are deployed with Capistrano / Webistrano •  The default deployment will push .svn directories to the servers GET http://www.strongspace.com/.svn/entries … dir 25376 http://svn.joyent.com/joyent/deprecated_repositories/www.strongspace/trunk/public http://svn.joyent.com/joyent Prevent .svn download 2006-04-14T03:06:39.902218Z <DirectoryMatch "^/.*/.svn/"> 34 ErrorDocument 403 /404.html justin@joyent.com Order allow,deny Deny from all … Satisfy All </DirectoryMatch> 17
  • 18. Cookie Session Storage Since Rails 2.0 the session data is stored in the cookie by default Base64(CGI::escape(SESSION-DATA))--HMAC(secret_key, SESSION-DATA) 18
  • 19. Cookie Session Storage Security implications •  The user can view the session data in plain text •  The HMAC can be brute-forced and arbitrary session data could be created •  Replay attacks are easier as you cannot flush the client-side session Countermeasures •  Don’t store important data in the session! •  Use a strong password, Rails already forces at least 30 characters •  Invalidate sessions after certain time on the server side … or just switch to another session storage 19
  • 20. Cookie Session Storage Rails default session secret Set HTTPS only cookies 20
  • 21. Cross-Site Scripting - XSS “The injection of HTML or client-side Scripts (e.g. JavaScript) by malicious users into web pages viewed by other users.” 21
  • 22. Cross-Site Scripting - XSS Cases of accepted user input •  No formatting allowed search query, user name, post title, … •  Formatting allowed post body, wiki page, … 22
  • 23. XSS - No Formatting Allowed (Rails 2.x) Use the Rails `h()` helper to HTML escape user input But using `h()` everywhere is easy to forget. Better, use safeERB, XSS Shield, or rails_xss plugins: http://agilewebdevelopment.com/plugins/safe_erb http://code.google.com/p/xss-shield/ http://github.com/NZKoz/rails_xss 23
  • 24. XSS - No Formatting Allowed (Rails 3) Rails 3 auto escapes strings in RHTML template Explicitly mark strings as HTML safe 24
  • 25. XSS - No Formatting Allowed (Rails 3) rails_xss Plugin •  Build-in in Rails 3 •  Introduces “Safe Buffer” concept •  Updates all the helpers to mark them as html_safe! •  Requires Erubis Install and get familiar with if on Rails 2.x http://github.com/NZKoz/rails_xss 25
  • 26. XSS - Formatting Allowed Two approaches Use custom tags that will translate to HTML (vBulletin tags, RedCloth, Textile, …) Use HTML and remove unwanted tags and attributes •  Blacklist - Rails 1.2 •  Whitelist - Rails 2.0 26
  • 27. XSS - Custom Tags Relying on the external syntax is not really secure Filter HTML anyhow 27
  • 28. XSS - HTML Filtering Use the Rails `sanitize()` helper Only effective with Rails > 2.0 (Whitelisting): •  Filters HTML nodes and attributes •  Removes protocols like “javascript:” •  Handles unicode/ascii/hex hacks 28
  • 29. XSS - HTML Filtering sanitize(html, options = {}) http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html 29
  • 30. XSS - HTML Filtering Utilize Tidy if you want to be more cautious 30
  • 31. Session Fixation Provide the user with a session that he shares with the attacker: 31
  • 32. Session Fixation Rails uses only cookie-based sessions Still, you should reset the session after a login The popular authentication plugins like restful_authentication are not doing this! 32
  • 33. Cross-Site Request Forgery - CSRF You visit a malicious site which has an image like this Only accepting POST does not really help 33
  • 34. CSRF Protection in Rails By default Rails > 2.0 will check all POST requests for a session token All forms generated by Rails will supply this token 34
  • 35. CSRF Protection in Rails Very useful and on-by-default, but make sure that •  GET requests are safe and idempotent •  Session cookies are not persistent (expires-at) 35
  • 36. SQL Injection The user’s input is not correctly escaped before using it in SQL statements 36
  • 37. SQL Injection Protection in Rails Always use the escaped form If you have to manually use a user-submitted value, use `quote()` 37
  • 38. SQL Injection Protection in Rails Take care with Rails < 2.1 Limit and offset are only escaped in Rails >= 2.1 ( MySQL special case ) 38
  • 39. JavaScript Hijacking http://my.evil.site/ JSON response The JSON response will be evaled by the Browser’s JavaScript engine. With a redefined `Array()` function this data can be sent back to http://my.evil.site 39
  • 40. JavaScript Hijacking Prevention •  Don’t put important data in JSON responses •  Use unguessable URLs •  Use a Browser that does not support the redefinition of Array & co, currently only FireFox 3 •  Don’t return a straight JSON response, prefix it with garbage: The Rails JavaScript helpers don’t support prefixed JSON responses 40
  • 42. Mass Assignment Handling in Controller A malicious user could just submit any value he wants 42
  • 43. Mass Assignment Use `attr_protected` and `attr_accessible` Vs. Start with `attr_protected` and migrate to `attr_accessible` because of the different default policies for new attributes. 43
  • 44. Rails Plugins Re-using code through plugins is very popular in Rails Plugins can have their problems too •  Just because somebody wrote and published a plugin it doesn’t mean the plugin is proven to be mature, stable or secure •  Popular plugins can also have security problems, e.g. restful_authentication •  Don’t use svn:externals to track external plugins, if the plugin’s home page is unavailable you cannot deploy your site 44
  • 45. Rails Plugins How to handle plugins •  Always do a code review of new plugins and look for obvious problems •  Track plugin announcements •  Track external sources with Piston, a wrapper around svn:externals http://piston.rubyforge.org/ 45
  • 47. Conclusion Rails has many security features enabled by default •  SQL quoting •  HTML sanitization •  CSRF protection The setup can be tricky to get right Rails is by no means a “web app security silver bullet” but adding security is easy and not a pain like in many other frameworks 47
  • 49. Peritor GmbH Blücherstaße 22 10961 Berlin Telefon: +49 (0)30 69 20 09 84 0 Telefax: +49 (0)30 69 20 09 84 9 Internet: www.peritor.com E-Mail: kontakt@peritor.com 49 Peritor GmbH - Alle Rechte vorbehalten 49