SlideShare a Scribd company logo
1 of 47
Download to read offline
Attacking MongoDB



               Firstov Mihail
What is it?

 MongoDB — is an open source document-oriented database system.

                         Features :

 1. Ad hoc queries.

 2. Indexing

 3. Replication

 4. Load balancing

 5. File storage

 6. Aggregation

 7. Server-side JavaScript execution

 8. Capped collections
Inside mongo source code

./mongod — Server in C++


                                                    ./mongo – official client in
                                                    C++ and JS

                           There are a lot of drivers for different
                           program languages:
                                         C
                                         C++
                                         Java
                                         Javascript
                                         .NET (C# F#, PowerShell, etc)
                                         Node.js
                                         Perl
                                         PHP
                                         Python
                                         Ruby
                                         Scala
Who use mongoDB
      List of some big companies that use mongoDB:

 1.   SAP

 2.   SourceForge (hosting for open source projects)

 3.   The New York Times

 4.   GitHub (social coding project)

 5.   Foursquare

 6.   Yandex
WTF is RESTful?


       A RESTful web service (also called a RESTful web
       API) is a web service implemented using HTTP and
       the principles of REST. It is a collection of
       resources, with four defined aspects
How I can discover it?
Default port is «28017».

If server was started without “—rest”, you can see this:
How I can discover it?
What kind of vulns are there?

   Execution of arbitrary code server JS

   Stored XSS in mongoDB log

   Stored XSS in queries journal

   Cross Site Request Forgery




                          Our SSJS code
Attack

                1) Send “<script>” with our javascript code
                                                                 Site with
                                                                 mongoDB
                                                                 driver support
 Hacker




                                                                                  Admin’s browser




     Hacker’s
     Server
                                                              MongoDB

                                                              --REST
Attack

                1) Send “<script>” with our javascript code
                                                                                  Site with
                                                                                  mongoDB
                                                                                  driver support
 Hacker




                                                                                                   Admin’s browser




                                                              2) Inject our script in
                                                              REST interface




     Hacker’s
     Server
                                                                             MongoDB

                                                                             --REST
Attack

                1) Send “<script>” with our javascript code
                                                                                  Site with
                                                                                  mongoDB
                                                                                  driver support
 Hacker




                                                                                                      Admin’s browser




                                                              2) Inject our script in
                                                              REST interface




     Hacker’s
     Server                                                                                        3) Exec our js-code in
                                                                             MongoDB               admin’s browser
                                                                             --REST
Attack

                 1) Send “<script>” with our javascript code
                                                                                   Site with
                                                                                   mongoDB
                                                                                   driver support
  Hacker




4) Send
SSJS                                                                                                   Admin’s browser
command to
our script


                                                               2) Inject our script in
                                                               REST interface




      Hacker’s
      Server                                                                                        3) Exec our js-code in
                                                                              MongoDB               admin’s browser
                                                                              --REST
Attack

                 1) Send “<script>” with our javascript code
                                                                                     Site with
                                                                                     mongoDB
                                                                                     driver support
  Hacker




4) Send
SSJS                                                                                                     Admin’s browser
command to
our script


                                                                 2) Inject our script in
                                                                 REST interface


                           5) Wait until admin’s browser check
                           our server for the new commands
                           (via JSONP)


      Hacker’s
      Server                                                                                          3) Exec our js-code in
                                                                                MongoDB               admin’s browser
                                                                                --REST
Attack

                 1) Send “<script>” with our javascript code
                                                                                     Site with
                                                                                     mongoDB
                                                                                     driver support
  Hacker




4) Send
SSJS                                                                                                            Admin’s browser
command to
our script


                                                                 2) Inject our script in
                                                                 REST interface            6) Our command gets executed

                           5) Wait until admin’s browser check
                           our server for the new commands
                           (via JSONP)


      Hacker’s
      Server                                                                                                 3) Exec our js-code in
                                                                                MongoDB                      admin’s browser
                                                                                --REST
Attack

                 1) Send “<script>” with our javascript code
                                                                                      Site with
                                                                                      mongoDB
                                                                                      driver support
  Hacker




4) Send
SSJS                                                                                                             Admin’s browser
command to                                                       7) Send answer to our sniffer
our script


                                                                  2) Inject our script in
                                                                  REST interface            6) Our command gets executed

                           5) Wait until admin’s browser check
                           our server for the new commands
                           (via JSONP)


      Hacker’s
      Server                                                                                                  3) Exec our js-code in
                                                                                 MongoDB                      admin’s browser
                                                                                 --REST
Attack

                 1) Send “<script>” with our javascript code
                                                                                          Site with
                                                                                          mongoDB
                                                                                          driver support
  Hacker




4) Send
SSJS         8) Print result                                                                                         Admin’s browser
command to   of executed                                             7) Send answer to our sniffer
our script   command


                                                                      2) Inject our script in
                                                                      REST interface            6) Our command gets executed

                               5) Wait until admin’s browser check
                               our server for the new commands
                               (via JSONP)


      Hacker’s
      Server                                                                                                      3) Exec our js-code in
                                                                                     MongoDB                      admin’s browser
                                                                                     --REST
Video
Where we can find it?
Stable CRASH
There are a lot of concepts of DoS attacks:
Interesting features

    Ls, cat and other admin functions work only with mongoDb console client.

    NativeHelper function helps you with system commands:




    You can get data in text/plain by reading db-files of mongoDB with any text editor.
Network interaction

Adding user:

                      Decrypted salt:




Source Code:
Network interaction

Captured packets:




All your data are belong to us:
Network interaction

Algorithm for sniff and brute force password :
  Sniff some packets                       Read string
  with mongoDB data                        from
                                           dictionary
                                                          key2 = md5(nonce + user +
                                                          md5(user + ":mongo:" + passw)),
                                                          where “passw” is string from dict
                   Get key, nonce, login
                   from this packet




       Look for auth                                            key == key2                    print user:passwd
       packet


                                                  false
                                                                                        true
                               found

                                                                                               Exit
Not found
Сетевое взаимодействие
Network interaction. MiTM attack


         1. Authorization
         query
                                     mongoDB


 admin




                            Hacker
Network interaction. MiTM attack


         1. Authorization
         query
                                                        mongoDB


 admin               2. Return special nonce
                     using which rainbow
                     tables were generated




                                               Hacker
Network interaction. MiTM attack


         1. Authorization
         query
                                                         mongoDB


 admin                2. Return special nonce
                      using which rainbow
                      tables were generated




                                                Hacker

         3. Client sends to us
         “key” and “login”
Network interaction. MiTM attack


                                                         4. Brute Force
         1. Authorization
                                                         password using pre-
         query
                                                         generated rainbow       mongoDB
                                                         tables for this nonce

 admin                2. Return special nonce
                      using which rainbow
                      tables were generated




                                                Hacker

         3. Client sends to us
         “key” and “login”
Network interaction. MiTM attack


                                                         4. Brute Force
         1. Authorization
                                                         password using pre-
         query
                                                         generated rainbow           mongoDB
                                                         tables for this nonce

 admin                2. Return special nonce
                      using which rainbow
                      tables were generated



                                                             5. Successfully login


                                                Hacker

         3. Client sends to us
         “key” and “login”
WTF is BSON?

What is it?                          Data types:

 BSON is a computer data                 string
 interchange format used mainly as       int
 a data storage and network              double
 transfer format in the MongoDB          DateTime
 database. The name "BSON" is            byte[]
 based on the term JSON and              bool
 stands for "Binary JSON".               null
                                         BsonObject
                                         BsonObject[]
   Example?
Overwriting variables

Some table with 2 documents:



Our query to database:


Injecting BSON document, and overwriting “isadmin” value:




Testing:
Reading memory
Exploit:
                 Length



In action:
Reading memory

In action:
Features of some programming languages




                      Ruby on Rails


                                nodejs


                                         PHP
Features of some programming languages




                Ruby on Rails
Features of some programming languages

Mass assignment in Ruby on Rails:
Features of some programming languages

Mass assignment in Ruby on Rails:
Features of some programming languages




                   NodeJS
Features of some programming languages

JSON injection в NodeJS + MongoDB:
                                            SEND

       VULNERABLE SOURCE CODE:


                                     RESULT QUERY:




                                                     Хакер 02/12 (157)
Features of some programming languages




                      PHP
Features of some programming languages

 Types of vulnerabilities:

     Bypass authorization via Array in php driver.

     Injecting SSJS code.

     Blind SSJS injecting, Time-based
Features of some programming languages

 As you know, php processes data from GPC as Array:


        password[$ne]=parol1




 There is find() function in the official driver for php:
Features of some programming languages


 And we got this query to mongoDB collection:




 With these techniques you can bypass authorization:
Features of some programming languages

 Injecting in SSJS.

 For example, we have this vulnerable code:
 $q = “function() { var loginn = ‘$login’; var passs = ‘$pass’; db.members.insert({id : 2,
 login : loginn, pass : passs}); }”;
 $db->execute($q);
 /

 We can see our login, id and pass in answer

 Trying to inject in SSJS query:




 As you can see, we rewrite “login” value by db.version() value
Features of some programming languages

 Sometimes we can’t see answer from our SSJS code.

 For this situations we can use Time-Based technique:




 A special script was written for this task.
NoSQL-injection Cheat Sheet


   db.getName() – Get current DB name

   db.members.count() – Get number of documents in the collection

   db.members.validate({ full : true}) – Get ALL information about this
    collection

   db.members.stats() – Get information about this collection

   db.members.remove() – remove all documents from current collection

   db.members.find().skip(0).limit(1) – Get documents from DB (Change only
    number in skip() function)

   db.getMongo().getDBNames().toString() – Get the list of all DBs

   db.members.find()[0][‘pass’] – Get “pass” value from current collection
Thanks!




        Firstov Mikhail
    mfirstov@ptsecurity.ru

More Related Content

Viewers also liked

World Wealth Report 2013
World Wealth Report 2013World Wealth Report 2013
World Wealth Report 2013
Wealth Partners
 
샤또 바티스트 고급 요양원
샤또 바티스트 고급 요양원샤또 바티스트 고급 요양원
샤또 바티스트 고급 요양원
Wealth Partners
 
Basquetebol iniciação
Basquetebol iniciaçãoBasquetebol iniciação
Basquetebol iniciação
matematica2011
 
Pete persistence
Pete persistencePete persistence
Pete persistence
hattie21
 
Top 8 parole officer resume samples
Top 8 parole officer resume samplesTop 8 parole officer resume samples
Top 8 parole officer resume samples
jomseros
 
Oliver S De Leon - Resume
Oliver S De Leon - ResumeOliver S De Leon - Resume
Oliver S De Leon - Resume
Oliver Leon
 

Viewers also liked (20)

Pueblo West LP
Pueblo West LPPueblo West LP
Pueblo West LP
 
World Wealth Report 2013
World Wealth Report 2013World Wealth Report 2013
World Wealth Report 2013
 
샤또 바티스트 고급 요양원
샤또 바티스트 고급 요양원샤또 바티스트 고급 요양원
샤또 바티스트 고급 요양원
 
How to create a Email Account with Mailbizz.com
How to create a Email Account with Mailbizz.comHow to create a Email Account with Mailbizz.com
How to create a Email Account with Mailbizz.com
 
Scan 1
Scan 1Scan 1
Scan 1
 
Scan 1.2
Scan 1.2Scan 1.2
Scan 1.2
 
FTP_User
FTP_UserFTP_User
FTP_User
 
Basquetebol iniciação
Basquetebol iniciaçãoBasquetebol iniciação
Basquetebol iniciação
 
The Indo-Lanka Link
The Indo-Lanka LinkThe Indo-Lanka Link
The Indo-Lanka Link
 
Créer et Gérer un Blog
Créer et Gérer un BlogCréer et Gérer un Blog
Créer et Gérer un Blog
 
Asp dot net e learning
Asp dot net e learningAsp dot net e learning
Asp dot net e learning
 
Ko tu zini par e drosibu
Ko tu zini par e drosibuKo tu zini par e drosibu
Ko tu zini par e drosibu
 
Pete persistence
Pete persistencePete persistence
Pete persistence
 
Globus Hospital Kanpur.
Globus Hospital Kanpur.Globus Hospital Kanpur.
Globus Hospital Kanpur.
 
Phoenix Contact
Phoenix ContactPhoenix Contact
Phoenix Contact
 
利用OpenSSL创建并验证证书
利用OpenSSL创建并验证证书利用OpenSSL创建并验证证书
利用OpenSSL创建并验证证书
 
XMPP, Jabber et Jingle
XMPP, Jabber et JingleXMPP, Jabber et Jingle
XMPP, Jabber et Jingle
 
Top 8 parole officer resume samples
Top 8 parole officer resume samplesTop 8 parole officer resume samples
Top 8 parole officer resume samples
 
Attacking MongoDB
Attacking MongoDBAttacking MongoDB
Attacking MongoDB
 
Oliver S De Leon - Resume
Oliver S De Leon - ResumeOliver S De Leon - Resume
Oliver S De Leon - Resume
 

Similar to Firstov attacking mongo db

Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
Rob Davarnia
 
Modern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScriptModern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScript
martinlippert
 
Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2
guest66dc5f
 
Develop Web20 With Rad - Tim Frnacis Sarika S
Develop Web20 With Rad - Tim Frnacis Sarika SDevelop Web20 With Rad - Tim Frnacis Sarika S
Develop Web20 With Rad - Tim Frnacis Sarika S
Roopa Nadkarni
 
6 develop web20_with_rad-tim_frnacis_sarika-s
6 develop web20_with_rad-tim_frnacis_sarika-s6 develop web20_with_rad-tim_frnacis_sarika-s
6 develop web20_with_rad-tim_frnacis_sarika-s
IBM
 
Programming SharePoint 2010 with Visual Studio 2010
Programming SharePoint 2010 with Visual Studio 2010Programming SharePoint 2010 with Visual Studio 2010
Programming SharePoint 2010 with Visual Studio 2010
Quang Nguyễn Bá
 

Similar to Firstov attacking mongo db (20)

Scalable XQuery Processing with Zorba on top of MongoDB
Scalable XQuery Processing with Zorba on top of MongoDBScalable XQuery Processing with Zorba on top of MongoDB
Scalable XQuery Processing with Zorba on top of MongoDB
 
Monogo db in-action
Monogo db in-actionMonogo db in-action
Monogo db in-action
 
Zedrick girish p_tryambakee 5102589493
Zedrick girish p_tryambakee 5102589493Zedrick girish p_tryambakee 5102589493
Zedrick girish p_tryambakee 5102589493
 
AFTAB AHMED.pptx
AFTAB AHMED.pptxAFTAB AHMED.pptx
AFTAB AHMED.pptx
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
Modern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScriptModern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScript
 
Isomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornIsomorphic JavaScript with Nashorn
Isomorphic JavaScript with Nashorn
 
Architecture of the Web browser
Architecture of the Web browserArchitecture of the Web browser
Architecture of the Web browser
 
Q con london2011-matthewwall-whyichosemongodbforguardiancouk
Q con london2011-matthewwall-whyichosemongodbforguardiancoukQ con london2011-matthewwall-whyichosemongodbforguardiancouk
Q con london2011-matthewwall-whyichosemongodbforguardiancouk
 
No More Mr. Nice Guy The MEAN Stack
No More Mr. Nice Guy   The MEAN StackNo More Mr. Nice Guy   The MEAN Stack
No More Mr. Nice Guy The MEAN Stack
 
Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2
 
Node JS
Node JSNode JS
Node JS
 
Jcon 2017 How to use Swagger to develop REST applications
Jcon 2017 How to use Swagger to develop REST applicationsJcon 2017 How to use Swagger to develop REST applications
Jcon 2017 How to use Swagger to develop REST applications
 
Develop Web20 With Rad - Tim Frnacis Sarika S
Develop Web20 With Rad - Tim Frnacis Sarika SDevelop Web20 With Rad - Tim Frnacis Sarika S
Develop Web20 With Rad - Tim Frnacis Sarika S
 
6 develop web20_with_rad-tim_frnacis_sarika-s
6 develop web20_with_rad-tim_frnacis_sarika-s6 develop web20_with_rad-tim_frnacis_sarika-s
6 develop web20_with_rad-tim_frnacis_sarika-s
 
Building Web Scale Apps with Docker and Mesos by Alex Rukletsov (Mesosphere)
Building Web Scale Apps with Docker and Mesos by Alex Rukletsov (Mesosphere)Building Web Scale Apps with Docker and Mesos by Alex Rukletsov (Mesosphere)
Building Web Scale Apps with Docker and Mesos by Alex Rukletsov (Mesosphere)
 
Programming SharePoint 2010 with Visual Studio 2010
Programming SharePoint 2010 with Visual Studio 2010Programming SharePoint 2010 with Visual Studio 2010
Programming SharePoint 2010 with Visual Studio 2010
 
Nodejs
NodejsNodejs
Nodejs
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 

More from DefconRussia

[DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC
[DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC [DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC
[DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC
DefconRussia
 
Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23
DefconRussia
 

More from DefconRussia (20)

[Defcon Russia #29] Борис Савков - Bare-metal programming на примере Raspber...
[Defcon Russia #29] Борис Савков -  Bare-metal programming на примере Raspber...[Defcon Russia #29] Борис Савков -  Bare-metal programming на примере Raspber...
[Defcon Russia #29] Борис Савков - Bare-metal programming на примере Raspber...
 
[Defcon Russia #29] Александр Ермолов - Safeguarding rootkits: Intel Boot Gua...
[Defcon Russia #29] Александр Ермолов - Safeguarding rootkits: Intel Boot Gua...[Defcon Russia #29] Александр Ермолов - Safeguarding rootkits: Intel Boot Gua...
[Defcon Russia #29] Александр Ермолов - Safeguarding rootkits: Intel Boot Gua...
 
[Defcon Russia #29] Алексей Тюрин - Spring autobinding
[Defcon Russia #29] Алексей Тюрин - Spring autobinding[Defcon Russia #29] Алексей Тюрин - Spring autobinding
[Defcon Russia #29] Алексей Тюрин - Spring autobinding
 
[Defcon Russia #29] Михаил Клементьев - Обнаружение руткитов в GNU/Linux
[Defcon Russia #29] Михаил Клементьев - Обнаружение руткитов в GNU/Linux[Defcon Russia #29] Михаил Клементьев - Обнаружение руткитов в GNU/Linux
[Defcon Russia #29] Михаил Клементьев - Обнаружение руткитов в GNU/Linux
 
Георгий Зайцев - Reversing golang
Георгий Зайцев - Reversing golangГеоргий Зайцев - Reversing golang
Георгий Зайцев - Reversing golang
 
[DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC
[DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC [DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC
[DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC
 
Cisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-oneCisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-one
 
Олег Купреев - Обзор и демонстрация нюансов и трюков из области беспроводных ...
Олег Купреев - Обзор и демонстрация нюансов и трюков из области беспроводных ...Олег Купреев - Обзор и демонстрация нюансов и трюков из области беспроводных ...
Олег Купреев - Обзор и демонстрация нюансов и трюков из области беспроводных ...
 
HTTP HOST header attacks
HTTP HOST header attacksHTTP HOST header attacks
HTTP HOST header attacks
 
Attacks on tacacs - Алексей Тюрин
Attacks on tacacs - Алексей ТюринAttacks on tacacs - Алексей Тюрин
Attacks on tacacs - Алексей Тюрин
 
Weakpass - defcon russia 23
Weakpass - defcon russia 23Weakpass - defcon russia 23
Weakpass - defcon russia 23
 
nosymbols - defcon russia 20
nosymbols - defcon russia 20nosymbols - defcon russia 20
nosymbols - defcon russia 20
 
static - defcon russia 20
static  - defcon russia 20static  - defcon russia 20
static - defcon russia 20
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
 
Vm ware fuzzing - defcon russia 20
Vm ware fuzzing  - defcon russia 20Vm ware fuzzing  - defcon russia 20
Vm ware fuzzing - defcon russia 20
 
Nedospasov defcon russia 23
Nedospasov defcon russia 23Nedospasov defcon russia 23
Nedospasov defcon russia 23
 
Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23
 
Miasm defcon russia 23
Miasm defcon russia 23Miasm defcon russia 23
Miasm defcon russia 23
 
Andrey Belenko, Alexey Troshichev - Внутреннее устройство и безопасность iClo...
Andrey Belenko, Alexey Troshichev - Внутреннее устройство и безопасность iClo...Andrey Belenko, Alexey Troshichev - Внутреннее устройство и безопасность iClo...
Andrey Belenko, Alexey Troshichev - Внутреннее устройство и безопасность iClo...
 
Sergey Belov - Покажите нам Impact! Доказываем угрозу в сложных условиях
Sergey Belov - Покажите нам Impact! Доказываем угрозу в сложных условияхSergey Belov - Покажите нам Impact! Доказываем угрозу в сложных условиях
Sergey Belov - Покажите нам Impact! Доказываем угрозу в сложных условиях
 

Firstov attacking mongo db

  • 1. Attacking MongoDB Firstov Mihail
  • 2. What is it? MongoDB — is an open source document-oriented database system. Features : 1. Ad hoc queries. 2. Indexing 3. Replication 4. Load balancing 5. File storage 6. Aggregation 7. Server-side JavaScript execution 8. Capped collections
  • 3. Inside mongo source code ./mongod — Server in C++ ./mongo – official client in C++ and JS There are a lot of drivers for different program languages: C C++ Java Javascript .NET (C# F#, PowerShell, etc) Node.js Perl PHP Python Ruby Scala
  • 4. Who use mongoDB List of some big companies that use mongoDB: 1. SAP 2. SourceForge (hosting for open source projects) 3. The New York Times 4. GitHub (social coding project) 5. Foursquare 6. Yandex
  • 5. WTF is RESTful? A RESTful web service (also called a RESTful web API) is a web service implemented using HTTP and the principles of REST. It is a collection of resources, with four defined aspects
  • 6. How I can discover it? Default port is «28017». If server was started without “—rest”, you can see this:
  • 7. How I can discover it?
  • 8. What kind of vulns are there?  Execution of arbitrary code server JS  Stored XSS in mongoDB log  Stored XSS in queries journal  Cross Site Request Forgery Our SSJS code
  • 9. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker Admin’s browser Hacker’s Server MongoDB --REST
  • 10. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker Admin’s browser 2) Inject our script in REST interface Hacker’s Server MongoDB --REST
  • 11. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker Admin’s browser 2) Inject our script in REST interface Hacker’s Server 3) Exec our js-code in MongoDB admin’s browser --REST
  • 12. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker 4) Send SSJS Admin’s browser command to our script 2) Inject our script in REST interface Hacker’s Server 3) Exec our js-code in MongoDB admin’s browser --REST
  • 13. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker 4) Send SSJS Admin’s browser command to our script 2) Inject our script in REST interface 5) Wait until admin’s browser check our server for the new commands (via JSONP) Hacker’s Server 3) Exec our js-code in MongoDB admin’s browser --REST
  • 14. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker 4) Send SSJS Admin’s browser command to our script 2) Inject our script in REST interface 6) Our command gets executed 5) Wait until admin’s browser check our server for the new commands (via JSONP) Hacker’s Server 3) Exec our js-code in MongoDB admin’s browser --REST
  • 15. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker 4) Send SSJS Admin’s browser command to 7) Send answer to our sniffer our script 2) Inject our script in REST interface 6) Our command gets executed 5) Wait until admin’s browser check our server for the new commands (via JSONP) Hacker’s Server 3) Exec our js-code in MongoDB admin’s browser --REST
  • 16. Attack 1) Send “<script>” with our javascript code Site with mongoDB driver support Hacker 4) Send SSJS 8) Print result Admin’s browser command to of executed 7) Send answer to our sniffer our script command 2) Inject our script in REST interface 6) Our command gets executed 5) Wait until admin’s browser check our server for the new commands (via JSONP) Hacker’s Server 3) Exec our js-code in MongoDB admin’s browser --REST
  • 17. Video
  • 18. Where we can find it?
  • 19. Stable CRASH There are a lot of concepts of DoS attacks:
  • 20. Interesting features  Ls, cat and other admin functions work only with mongoDb console client.  NativeHelper function helps you with system commands:  You can get data in text/plain by reading db-files of mongoDB with any text editor.
  • 21. Network interaction Adding user: Decrypted salt: Source Code:
  • 22. Network interaction Captured packets: All your data are belong to us:
  • 23. Network interaction Algorithm for sniff and brute force password : Sniff some packets Read string with mongoDB data from dictionary key2 = md5(nonce + user + md5(user + ":mongo:" + passw)), where “passw” is string from dict Get key, nonce, login from this packet Look for auth key == key2 print user:passwd packet false true found Exit Not found
  • 25. Network interaction. MiTM attack 1. Authorization query mongoDB admin Hacker
  • 26. Network interaction. MiTM attack 1. Authorization query mongoDB admin 2. Return special nonce using which rainbow tables were generated Hacker
  • 27. Network interaction. MiTM attack 1. Authorization query mongoDB admin 2. Return special nonce using which rainbow tables were generated Hacker 3. Client sends to us “key” and “login”
  • 28. Network interaction. MiTM attack 4. Brute Force 1. Authorization password using pre- query generated rainbow mongoDB tables for this nonce admin 2. Return special nonce using which rainbow tables were generated Hacker 3. Client sends to us “key” and “login”
  • 29. Network interaction. MiTM attack 4. Brute Force 1. Authorization password using pre- query generated rainbow mongoDB tables for this nonce admin 2. Return special nonce using which rainbow tables were generated 5. Successfully login Hacker 3. Client sends to us “key” and “login”
  • 30. WTF is BSON? What is it? Data types: BSON is a computer data string interchange format used mainly as int a data storage and network double transfer format in the MongoDB DateTime database. The name "BSON" is byte[] based on the term JSON and bool stands for "Binary JSON". null BsonObject BsonObject[] Example?
  • 31. Overwriting variables Some table with 2 documents: Our query to database: Injecting BSON document, and overwriting “isadmin” value: Testing:
  • 32. Reading memory Exploit: Length In action:
  • 34. Features of some programming languages Ruby on Rails nodejs PHP
  • 35. Features of some programming languages Ruby on Rails
  • 36. Features of some programming languages Mass assignment in Ruby on Rails:
  • 37. Features of some programming languages Mass assignment in Ruby on Rails:
  • 38. Features of some programming languages NodeJS
  • 39. Features of some programming languages JSON injection в NodeJS + MongoDB: SEND VULNERABLE SOURCE CODE: RESULT QUERY: Хакер 02/12 (157)
  • 40. Features of some programming languages PHP
  • 41. Features of some programming languages Types of vulnerabilities: Bypass authorization via Array in php driver. Injecting SSJS code. Blind SSJS injecting, Time-based
  • 42. Features of some programming languages As you know, php processes data from GPC as Array: password[$ne]=parol1 There is find() function in the official driver for php:
  • 43. Features of some programming languages And we got this query to mongoDB collection: With these techniques you can bypass authorization:
  • 44. Features of some programming languages Injecting in SSJS. For example, we have this vulnerable code: $q = “function() { var loginn = ‘$login’; var passs = ‘$pass’; db.members.insert({id : 2, login : loginn, pass : passs}); }”; $db->execute($q); / We can see our login, id and pass in answer Trying to inject in SSJS query: As you can see, we rewrite “login” value by db.version() value
  • 45. Features of some programming languages Sometimes we can’t see answer from our SSJS code. For this situations we can use Time-Based technique: A special script was written for this task.
  • 46. NoSQL-injection Cheat Sheet  db.getName() – Get current DB name  db.members.count() – Get number of documents in the collection  db.members.validate({ full : true}) – Get ALL information about this collection  db.members.stats() – Get information about this collection  db.members.remove() – remove all documents from current collection  db.members.find().skip(0).limit(1) – Get documents from DB (Change only number in skip() function)  db.getMongo().getDBNames().toString() – Get the list of all DBs  db.members.find()[0][‘pass’] – Get “pass” value from current collection
  • 47. Thanks! Firstov Mikhail mfirstov@ptsecurity.ru