SlideShare a Scribd company logo
Rails & Security
        People should know it

  Insecure-by-default means insecure

     http://homakov.blogspot.com
Agenda
●   GET Accessible Actions(method “match”, CSRF)
●   Mass Assignment(attr_accessible, “SQL Inject”)
●   JS(ON) and DOM Injects, Responders and XSS
●   Regular Expressions and Validators
●   Common Tips
●   Headers
●   [bonus?] OAuth
Rails ARE Secure
●   CSRF Protection by default
    (authenticity_token)
●   XSS Protection(HtmlSafe, sanitize by
    default)
●   SQL Injects are impossible(active record)
●   Hundreds of commits with security
    improvements, etc
PHP(and others) is not
●   if I see PHP site with (proper)CSRF
    protection than .. it's facebook.com
●   SQL Injects, XSS, includes, zomg etc
●   "secure by default" just impossible

thus rails is more secure than most php sites
are...
BUT
Rails and security
case 1
#routes.rb
#match usage is a common mistake
match “/follow”, to: “followings#create”
match “/followers, to: “followings#index”
case 1

Hey, “match” means GET too. GET means no csrf protection!
case 1
>This commit disallows calling +match+ without an HTTP
verb constraint by default. To explicitly match all verbs, this
commit also adds a :via => :all option to +match+.
(@wycats)

#update code:
post “/follow”, to: “followings#create”
get “/followers, to: “followings#index”

match “/getpost_endpoint”, via: :all, to: “etc#etc”
case 1 tips
Make sure to set “post” for state-changing
requests.

Avoid using of “match”

Use “get” for all data retrieval requests.

Scope your routes, be RESTful, please.
case 2
#comments/index.haml
:javascript
  var comments = #{@comments.to_json}

OR

:javascript
  var value = "#{current_user.name}"
case 2
@comments = {k:"</script><script>alert(1)
</script>"}

JSON Encoder and ':javascript' (:css too!)
both don't escape anything - output is RAW.
case 2



XSS?!
case 2 tips
Update rails to 4(now html entities are
escaped by default) or set manually
ActiveSupport.escape_html_entities_in_html
= true
in initializers or don't use .to_json in
templates.
case 3
#comments/index.haml
:javascript
  var data = #{@data.to_json} #or getJSON
  $('.datacontainer').html(data.body);
case 3
Pitfall. That is a pure DOM XSS - you didn't
sanitize it! Escaping u only helps JSON
parser but you should sanitize it before you
insert into DOM

Don't trust/use any input param until you
sanitized it.
case 3
case 3 tips
Use $.text()/innerText instead of $.html()
/innerHTML when possible, always sanitize
any user input even in JS(Rails just
escapes). I strongly recommend this patch:

ActiveSupport::JSON::Encoding::
ESCAPED_CHARS.merge! '<' => '&lt;'
case 4
params[:user][:url]="http://#{params[:user][:
url]}" unless params[:user][:url] =~ /^https?/

#update attributes
case 4
case 4 tips
Keep in mind - in ruby $^ always match new
lines. Your manuals and books lie. Use Az
This passes:

javascript:alert(1)/*
http://hi.com
*/
added warning/exception in RoR
case 5
#in application_controller.rb
skip_before_filter :verify_authenticity_token
case 5 tips
protect_from_forgery is a MUST. It is a
hassle to deal with tokens but don't be
stupid.

No, presence of authenticity_token input
doesn't scare a hacker.
case 6
found an XSS for auto_link, remember,
always *whitelist* everything - protocols too

javascript://%0Aalert(1)

Update your bundle, if you use auto_link or
rails_autolink gem
Rails and security
case 7
class PublicKey < ActiveRecord::Base
 #attr_accessible, where are you...
end
case 7
case 7
Github and Assembla shared the same
vulnerability.
It was easy to steal or push code into
anybody’s repo 'dropping' your public key.

Also you could(still can) set
“created/updated_at” to 3012 in *really* a lot
of applications to have fun and get the 1st
place in 'order by *_at'
case 7 tips
If use update_attributes/new/create+hash -
you should set attr_accessible(If you don’t
use mass assignment - don’t care.)
gem 'strong_parameters'
whitelist_attributes = true by default.
it takes slightly more time to write an app but
it’s worth it.
IT IS NOT attr_accessor :±
case 8
#hand-made jsonp
json = Order.all.to_json
render text: "#{params[:callback]}(#{json})"

https://api.github.com/user/repos?
callback=leak
case 8 tips
don't give out private data via JSONP

avoid - render text: contains_user_input

XSS - ?callback=<script>..</script>
use - render json: data, callback: params[:
cb]
case 9 - CVE-2012-2660
Mass assignment[extended edition]. You
can send nested arrays/hashes in any
param.
params[:token] can be a huge array(brute):

?token[]=1&token[]=2&token[]=3...

it also may contain nils!
?token[] <- nil
case 9 - CVE-2012-2660
Change
User.find_by_token(params[:token]) and
User.where(token: params[:token])

use explicit casting
params[:token].to_s
common tips
●   use system('ls', '.') instead of `ls .`
●   before_filter{headers['X-Frame-Options']
    ='SAMEORIGIN'}#application_controller.
    rb
●   hide config/initializers/secret_token.rb
●   obvious: check permissions
●   WHITELIST
●   RTFM
#DISCUSS
Security is not developers' business.
Web is poorly designed: Clickjacking, CSRF
bonus
bonus OAuth
CSRF + GET.
code/token
getting into master-account with no
fingerprints.

omniauth fb strategy vulnerability

depends on server side logic
bonus OAuth
http://soundcloud.
com/connect/facebook/create?
code=AQBXeR_dORPlx4RRUt_YzJ6Rdg0
eb9CWHek8J2fB4vqfdNPvznmx-d-
J36gGQlXJICRdfqFb9a_VWqke4ZamE2H
ytlXtK5c6sMaOQUQLPPhSWNv3v8z-
ze6hdT6x4LNSXC_-
jxGRecjw1WTmifzO_rBFaDI86xPo2YH3k_
ehEtw5wM9rVduymjZumXkoistF7I9g2MQ
bonus OAuth
Mitigation: CSRF token in 'state' param.
Checking
$_SESSION['state']==$_REQUEST
['session'] IS NOT WORKING

Check existence and equality both.

OR use client side JS based authentication.
references
[old] http://www.rorsecurity.info/

http://guides.rubyonrails.org/security.html

http://developers.facebook.
com/docs/authentication/server-side/

get new stuff 1st!: homakov.blogspot.com
Teh Edn.




Y U NO PAY ME FOR SECURITY AUDIT?

More Related Content

PDF
PHP Secure Programming
PDF
Intro to Php Security
PPS
PHP Security
PDF
RSpec 2 Best practices
PPTX
2019-08-23 API contract testing with Dredd
PDF
Web Application Security
PDF
Automated testing with RSpec
KEY
PHP security audits
PHP Secure Programming
Intro to Php Security
PHP Security
RSpec 2 Best practices
2019-08-23 API contract testing with Dredd
Web Application Security
Automated testing with RSpec
PHP security audits

What's hot (20)

ODP
Security In PHP Applications
PDF
Php Security
PDF
Testing Ruby with Rspec (a beginner's guide)
PPT
PHP Security
PPT
Ruby on Rails testing with Rspec
PDF
MeetJS Summit 2016: React.js enlightenment
PDF
Rspec API Documentation
PDF
Get Started with RabbitMQ (CoderCruise 2017)
PPTX
Rspec presentation
PDF
Automated code audits
PPT
XSS - Attacks & Defense
PDF
RSpec 3: The new, the old, the good
PDF
Better Code through Lint and Checkstyle
PDF
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
PPT
Practical Ext JS Debugging
PPT
PDF
Re-analysis of Umbraco code
PDF
TDD with phpspec2
PPT
&lt;img src="xss.com">
PDF
10 Rules for Safer Code
Security In PHP Applications
Php Security
Testing Ruby with Rspec (a beginner's guide)
PHP Security
Ruby on Rails testing with Rspec
MeetJS Summit 2016: React.js enlightenment
Rspec API Documentation
Get Started with RabbitMQ (CoderCruise 2017)
Rspec presentation
Automated code audits
XSS - Attacks & Defense
RSpec 3: The new, the old, the good
Better Code through Lint and Checkstyle
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
Practical Ext JS Debugging
Re-analysis of Umbraco code
TDD with phpspec2
&lt;img src="xss.com">
10 Rules for Safer Code
Ad

Viewers also liked (20)

PPTX
Schmitzrollingeyeballs
XLS
Bang khao sat phan loai
PPTX
PPTX
PPT
Lasten ja nuorten verkonkaytto
PPTX
Tic.document
PPTX
OnCentral: Telling stories in South LA
PPTX
Inventory Deep Dive
PPTX
Movement in brazil
PPTX
Edmonton oilers ppt
PPTX
Spiceworks Unplugged AMD-Exclusive
KEY
social media week 3: microblogging
PDF
PDF
PPT
Promociones vanguard
PPTX
Brazil
PDF
Creating house style
Schmitzrollingeyeballs
Bang khao sat phan loai
Lasten ja nuorten verkonkaytto
Tic.document
OnCentral: Telling stories in South LA
Inventory Deep Dive
Movement in brazil
Edmonton oilers ppt
Spiceworks Unplugged AMD-Exclusive
social media week 3: microblogging
Promociones vanguard
Brazil
Creating house style
Ad

Similar to Rails and security (20)

PPT
General Principles of Web Security
PDF
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
PPT
Eight simple rules to writing secure PHP programs
PDF
10 Rules for Safer Code [Odoo Experience 2016]
PPT
PDF
Charla EHU Noviembre 2014 - Desarrollo Web
PDF
My app is secure... I think
PDF
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
ODP
2009 Barcamp Nashville Web Security 101
PPT
XSS Primer - Noob to Pro in 1 hour
ODP
Top 10 Web Security Vulnerabilities
PPTX
REST with Eve and Python
PPT
PHPUG Presentation
PPT
Joomla security nuggets
PPTX
Good practices for PrestaShop code security and optimization
PDF
주로사용되는 Xss필터와 이를 공격하는 방법
PDF
Wt unit 2 ppts client side technology
PDF
Wt unit 2 ppts client sied technology
KEY
[Coscup 2012] JavascriptMVC
PPT
Defending Against Attacks With Rails
General Principles of Web Security
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Eight simple rules to writing secure PHP programs
10 Rules for Safer Code [Odoo Experience 2016]
Charla EHU Noviembre 2014 - Desarrollo Web
My app is secure... I think
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
2009 Barcamp Nashville Web Security 101
XSS Primer - Noob to Pro in 1 hour
Top 10 Web Security Vulnerabilities
REST with Eve and Python
PHPUG Presentation
Joomla security nuggets
Good practices for PrestaShop code security and optimization
주로사용되는 Xss필터와 이를 공격하는 방법
Wt unit 2 ppts client side technology
Wt unit 2 ppts client sied technology
[Coscup 2012] JavascriptMVC
Defending Against Attacks With Rails

More from Andrey Tokarchuk (20)

PDF
Vrealize automotion
PDF
Vmware any-cloud
PDF
Nvidia grid-2
PDF
Интеллектуальная собственность в IT
PDF
Демонизированный PHP - before it was cool
PDF
Тестируем инфраструктуру как код
PDF
OpenStack сегодня
PDF
Релиз PHP7 - что нас ждет в октябре 2015
PPT
писатели юбиляры
PDF
My sql 5.6-new-stable-mmug
PDF
Модули в zend framework 2.ростислав михайлив
PDF
Zend cache evolution.владимир дубина
PDF
Очередь задач и многопоточность с помощью gearman и zf.станислав прокопив
PDF
Highload не кусается.антон шевчук
PDF
Соблазнительные формы в zend framework 2.даниил кожемяко
PDF
mms или как просто работать с моделями данных.иван кутузов
PDF
Cобытийная модель zend framework 2, event manager. александр вронский
PDF
PDF
Vrealize automotion
Vmware any-cloud
Nvidia grid-2
Интеллектуальная собственность в IT
Демонизированный PHP - before it was cool
Тестируем инфраструктуру как код
OpenStack сегодня
Релиз PHP7 - что нас ждет в октябре 2015
писатели юбиляры
My sql 5.6-new-stable-mmug
Модули в zend framework 2.ростислав михайлив
Zend cache evolution.владимир дубина
Очередь задач и многопоточность с помощью gearman и zf.станислав прокопив
Highload не кусается.антон шевчук
Соблазнительные формы в zend framework 2.даниил кожемяко
mms или как просто работать с моделями данных.иван кутузов
Cобытийная модель zend framework 2, event manager. александр вронский

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
A Presentation on Artificial Intelligence
PDF
Machine learning based COVID-19 study performance prediction
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Modernizing your data center with Dell and AMD
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
20250228 LYD VKU AI Blended-Learning.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Building Integrated photovoltaic BIPV_UPV.pdf
Big Data Technologies - Introduction.pptx
Electronic commerce courselecture one. Pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
A Presentation on Artificial Intelligence
Machine learning based COVID-19 study performance prediction
Network Security Unit 5.pdf for BCA BBA.
Chapter 3 Spatial Domain Image Processing.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
The Rise and Fall of 3GPP – Time for a Sabbatical?
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Modernizing your data center with Dell and AMD

Rails and security