SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie Rails and 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)
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 programs
Aleksandr Yampolskiy
 
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
heikowebers
 
Joomla security nuggets
Joomla security nuggetsJoomla security nuggets
Joomla security nuggets
guestbd1cdca
 
주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법
guestad13b55
 

Ähnlich wie 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
 

Mehr von Andrey Tokarchuk

Интеллектуальная собственность в IT
Интеллектуальная собственность в ITИнтеллектуальная собственность в IT
Интеллектуальная собственность в IT
Andrey Tokarchuk
 
Демонизированный PHP - before it was cool
Демонизированный PHP - before it was coolДемонизированный PHP - before it was cool
Демонизированный PHP - before it was cool
Andrey Tokarchuk
 
Тестируем инфраструктуру как код
Тестируем инфраструктуру как кодТестируем инфраструктуру как код
Тестируем инфраструктуру как код
Andrey Tokarchuk
 
Релиз PHP7 - что нас ждет в октябре 2015
Релиз PHP7 - что нас ждет в октябре 2015Релиз PHP7 - что нас ждет в октябре 2015
Релиз PHP7 - что нас ждет в октябре 2015
Andrey Tokarchuk
 
писатели юбиляры
писатели юбилярыписатели юбиляры
писатели юбиляры
Andrey Tokarchuk
 

Mehr von 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
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

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?