SlideShare uma empresa Scribd logo
1 de 41
Baixar para ler offline
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
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
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?

Mais conteúdo relacionado

Mais procurados

Security In PHP Applications
Security In PHP ApplicationsSecurity In PHP Applications
Security In PHP ApplicationsAditya Mooley
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Vysakh Sreenivasan
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with RspecBunlong Van
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentArtur Szott
 
Rspec API Documentation
Rspec API DocumentationRspec API Documentation
Rspec API DocumentationSmartLogic
 
Get Started with RabbitMQ (CoderCruise 2017)
Get Started with RabbitMQ (CoderCruise 2017)Get Started with RabbitMQ (CoderCruise 2017)
Get Started with RabbitMQ (CoderCruise 2017)James Titcumb
 
Rspec presentation
Rspec presentationRspec presentation
Rspec presentationMyo T Kyaw
 
Automated code audits
Automated code auditsAutomated code audits
Automated code auditsDamien Seguy
 
RSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodRSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodmglrnm
 
Better Code through Lint and Checkstyle
Better Code through Lint and CheckstyleBetter Code through Lint and Checkstyle
Better Code through Lint and CheckstyleMarc Prengemann
 
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseCppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseAndrey Karpov
 
Practical Ext JS Debugging
Practical Ext JS DebuggingPractical Ext JS Debugging
Practical Ext JS DebuggingShea Frederick
 
Re-analysis of Umbraco code
Re-analysis of Umbraco codeRe-analysis of Umbraco code
Re-analysis of Umbraco codePVS-Studio
 
10 Rules for Safer Code
10 Rules for Safer Code10 Rules for Safer Code
10 Rules for Safer CodeQuang Ngoc
 

Mais procurados (20)

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

Destaque (20)

Schmitzrollingeyeballs
SchmitzrollingeyeballsSchmitzrollingeyeballs
Schmitzrollingeyeballs
 
Delta
DeltaDelta
Delta
 
Bang khao sat phan loai
Bang khao sat phan loaiBang khao sat phan loai
Bang khao sat phan loai
 
Prueva
PruevaPrueva
Prueva
 
Prueva
PruevaPrueva
Prueva
 
Lasten ja nuorten verkonkaytto
Lasten ja nuorten verkonkayttoLasten ja nuorten verkonkaytto
Lasten ja nuorten verkonkaytto
 
Tic.document
Tic.documentTic.document
Tic.document
 
OnCentral: Telling stories in South LA
OnCentral: Telling stories in South LAOnCentral: Telling stories in South LA
OnCentral: Telling stories in South LA
 
Inventory Deep Dive
Inventory Deep DiveInventory Deep Dive
Inventory Deep Dive
 
Movement in brazil
Movement in brazilMovement in brazil
Movement in brazil
 
Edmonton oilers ppt
Edmonton oilers pptEdmonton oilers ppt
Edmonton oilers ppt
 
Spiceworks Unplugged AMD-Exclusive
Spiceworks Unplugged AMD-Exclusive Spiceworks Unplugged AMD-Exclusive
Spiceworks Unplugged AMD-Exclusive
 
social media week 3: microblogging
social media week 3: microbloggingsocial media week 3: microblogging
social media week 3: microblogging
 
Nsx 6.2
Nsx 6.2Nsx 6.2
Nsx 6.2
 
Smart School
Smart SchoolSmart School
Smart School
 
Promociones vanguard
Promociones vanguardPromociones vanguard
Promociones vanguard
 
225
225225
225
 
Brazil
BrazilBrazil
Brazil
 
Beta
BetaBeta
Beta
 
Creating house style
Creating  house styleCreating  house style
Creating house style
 

Semelhante a Rails and security

General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsAleksandr Yampolskiy
 
10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]Olivier Dony
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebMikel Torres Ugarte
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayConRuby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayConheikowebers
 
2009 Barcamp Nashville Web Security 101
2009 Barcamp Nashville   Web Security 1012009 Barcamp Nashville   Web Security 101
2009 Barcamp Nashville Web Security 101brian_dailey
 
XSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hourXSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hoursnoopythesecuritydog
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesCarol McDonald
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and PythonPiXeL16
 
Joomla security nuggets
Joomla security nuggetsJoomla security nuggets
Joomla security nuggetsguestbd1cdca
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationPrestaShop
 
주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법guestad13b55
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Defending Against Attacks With Rails
Defending Against Attacks With RailsDefending Against Attacks With Rails
Defending Against Attacks With RailsTony Amoyal
 

Semelhante a Rails and security (20)

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

Mais de Andrey Tokarchuk

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

Mais de Andrey Tokarchuk (20)

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

Último

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Rails and security

  • 1. Rails & Security People should know it Insecure-by-default means insecure http://homakov.blogspot.com
  • 2. 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
  • 3. 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
  • 4. 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...
  • 5. BUT
  • 6.
  • 7. case 1 #routes.rb #match usage is a common mistake match “/follow”, to: “followings#create” match “/followers, to: “followings#index”
  • 8. case 1 Hey, “match” means GET too. GET means no csrf protection!
  • 9. 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”
  • 10. 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.
  • 11. case 2 #comments/index.haml :javascript var comments = #{@comments.to_json} OR :javascript var value = "#{current_user.name}"
  • 12. case 2 @comments = {k:"</script><script>alert(1) </script>"} JSON Encoder and ':javascript' (:css too!) both don't escape anything - output is RAW.
  • 14. 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.
  • 15. case 3 #comments/index.haml :javascript var data = #{@data.to_json} #or getJSON $('.datacontainer').html(data.body);
  • 16. 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.
  • 18. 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;'
  • 19. case 4 params[:user][:url]="http://#{params[:user][: url]}" unless params[:user][:url] =~ /^https?/ #update attributes
  • 21. 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
  • 23. 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.
  • 24. 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
  • 25.
  • 26. case 7 class PublicKey < ActiveRecord::Base #attr_accessible, where are you... end
  • 28. 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'
  • 29. 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 :±
  • 30. case 8 #hand-made jsonp json = Order.all.to_json render text: "#{params[:callback]}(#{json})" https://api.github.com/user/repos? callback=leak
  • 31. 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]
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. #DISCUSS Security is not developers' business. Web is poorly designed: Clickjacking, CSRF
  • 36. bonus
  • 37. bonus OAuth CSRF + GET. code/token getting into master-account with no fingerprints. omniauth fb strategy vulnerability depends on server side logic
  • 39. 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.
  • 41. Teh Edn. Y U NO PAY ME FOR SECURITY AUDIT?